Compare commits

..

28 Commits
beta_1 ... main

Author SHA1 Message Date
thw 31b28652db Release v0.8.0-beta: Watten, tutorial framework, soul profiles & UI font selector 2026-11-25 22:55:44 +01:00
thw 8acff1058a feat: add 10er raus, Pyramid & TriPeaks Solitaire, custom game icons and Linux DB path fix 2026-11-24 20:50:08 +01:00
thw c5e303db9f release(v0.6.0-beta): modularize codebase (<500 LOC/file), unify stats hub & refine win FX
Release v0.6.0-beta:
- Strikte Modularisierung (<500 Zeilen pro Datei, 1 Klasse pro Modul, pyscn Health Score 97/100).
- Gemeinsame Basis-Klassen extrahiert: SolitaireMenuBase, SolitaireTableController, SolitaireSessionGuard, SolitaireCanvasInput, SolitaireOutcomeFlow, LuckPouchMenuBase, CasinoArenaBase & CasinoResultDialogBase.
- UnifiedStatsView: kategorisierter Statistik-Hub (Glück, Solitaire, Bayerische Spiele, Gesellschaft) ohne Gesamt-Ansicht.
- PokerResultDialog auf das Gothic-Canvas-Rahmendesign gehoben.
- EndgameFxOverlay: Feuerwerksraketen entfernt, direkter Spawn von Fledermaus- und Kürbis-Explosionen.
2026-11-22 23:11:52 +01:00
thw 9492b92e80 refactor(arch,ui,stats): modularize codebase (<500 LOC/file), unify stats hub & refine win FX
Großes Architektur-, Deduplizierungs- & UI-Release:
- Strikte Modularisierung (<500 Zeilen pro Datei, 1 Klasse pro Modul, pyscn Health Score 97/100).
- Gemeinsame Basis-Klassen extrahiert: SolitaireMenuBase, SolitaireTableController, SolitaireSessionGuard, SolitaireCanvasInput, SolitaireOutcomeFlow, LuckPouchMenuBase, CasinoArenaBase & CasinoResultDialogBase.
- UnifiedStatsView: kategorisierter Statistik-Hub (Glück, Solitaire, Bayerische Spiele, Gesellschaft) ohne Äpfel-mit-Birnen-Gesamtansicht.
- PokerResultDialog auf das Gothic-Canvas-Rahmendesign gehoben.
- EndgameFxOverlay: Feuerwerksraketen entfernt, direkter Spawn von Fledermaus- und Kürbis-Explosionen.
2026-11-22 23:07:57 +01:00
thw 42bf545b35 feat(settings,db,auth,ui): add portable DB relocation, online account login, full-screen SettingsView & error overlay
Architektur-, UI- & Aufräum-Update:
- DbLocator + Database: freie Speicherortwahl beim Erstnutzer, Live-Laden & atomarer Umzug (SQLite Backup API) inkl. Selbst-Speicherung des Pfads in settings.
- OnlineSessionClient & LoginView: Modus-Weiche zwischen lokalem Profil und Online-Einzelaccount (URL inkl. Port oder IP + Port, REST/JSON & TCP/JSON).
- SettingsView: AudioSettingsDialog durch vollflächige, responsive 1-/2-Spalten-Ansicht ersetzt (inkl. verlustfreiem In-Game-Modus) und redundante Sprach-Buttons entfernt.
- ErrorReportOverlay: globaler Crash-Handler für unbehandelte Exceptions mit Copy-to-Clipboard und crash_errors.log.
- i18n & Cleanup: nicht unterstützte Sonderzeichen/Glyphen aus allen SQL-Dateien entfernt und verwaiste Altdateien bereinigt.
2026-11-22 04:26:44 +01:00
thw 22aef15efc feat(blackjack,poker): integrate EndgameFxOverlay, fix split-pot tie handling, and reveal showdown bot cards
Blackjack & Poker Endgame-Integration:
- EndgameFxOverlay vor BlackjackResultDialog (inkl. Instant-777-Sieg) und PokerResultDialog eingebunden.
- Echten Split-Pot ohne Netto-Gewinn/Verlust in Poker sauber als Unentschieden (player_won = None) behandelt, sodass keine fehlerhafte Niederlagen-Animation auslöst.
- Aufgedeckte Bot-Hole-Cards im Poker-Showdown direkt in den Tisch-Boxen während der Vorschalt-Animation eingeblendet und Hand-Referenz-Button im Showdown ausgeblendet.
- play_fx=False bei Sprachwechsel und Resume-Ständen gesetzt, um doppelte Animationen zu verhindern.
2026-11-22 00:28:06 +01:00
thw 88f957b5ed chore: sync LICENSE.md removal from public repo 2026-11-22 00:13:15 +01:00
thw 547c13ce7f feat(solitaire,ui): add Z-order card hover peek, single-tap move setting, ModalVeil, and EndgameFxOverlay
Solitaire UX & Bedienhilfen:
- CardHoverZoom (games/solitaire/base/card_hover_zoom.py) eingeführt: Hebt offene Karten beim Überfahren dezent an und vergrößert sie leicht unter Beibehaltung der exakten Z-Order im Stapel, sodass aufliegende Folgekarten sichtbar bleiben (inkl. 3er-Ablagefächer in Klondike und blockierter Zwischenkarten in FreeCell/Spider).
- Persistente Einstellung "Einfacher Klick zum Schieben" / "Single tap to move" (games/solitaire/base/solitaire_tap_prefs.py) ergänzt: Kurze Einzelklicks (<= 0.28s) führen automatisch Züge aus, während längeres Halten ignoriert wird und Drag & Drop uneingeschränkt erhalten bleibt.
- AudioSettingsDialog (view/dialogs/audio_settings_dialog.py) um den neuen GothSwitch erweitert, Layout auf 768p-Kompatibilität (DLG_H = 656) optimiert und alle Dialogtexte sauber auf base_i18n (01_allgemein.sql) umgestellt.
- FreeCellTableView, KlondikeTableView und SpiderTableView auf CardHoverZoom, Single-Tap-Steuerung, zentrale GothTopbar-Statistik-Endpunkte und SolitaireBottomBar-Overflow-Buttons aktualisiert.

Überarbeitetes Spielende & Modal-Architektur:
- ModalVeil (view/widgets/modal_veil.py) implementiert: Dunkelt das gesperrte Spielfeld halbtransparent ab, hebt aktive Dialoge garantiert über alle UI-Leisten und blockiert Eingaben sowie Tastenkürzel im Hintergrund.
- EndgameFxOverlay (view/widgets/endgame_fx_overlay.py) implementiert: Spielt vor dem Ergebnis-Dialog auf dem gesperrten Tisch Alpha-Kanal-Animationen ab (Sieg: firework_start.gif unten links + zufällig verteilte bat_explosion.gif / pumpkin_explosion.gif; Niederlage: zufällig verteilte foul_pumpkin.gif) und wechselt erst per Klick zum Result-Screen.
- ResourceManager und AssetManager um den Pfad resources/images/win_lose/, RGBA-GIF-Sequenz-Caching inkl. Original-Frame-Dauern, abgedunkelte Veil-Texturen und Startup-Preloading erweitert.
- Eingebettete GIF-Animationen aus SolitaireModalDialog, BlackjackResultDialog und PokerResultDialog vollständig entfernt und alle drei Ergebnis-Fenster auf ModalVeil umgestellt.
2026-11-22 00:02:21 +01:00
kuro 9ef9318a51 Delete LICENSE 2026-11-21 02:09:34 +00:00
kuro 4afd260bab Delete LICENSE.md 2026-11-21 02:09:17 +00:00
kuro 34678665a8 Delete LICENSE.md 2026-11-21 01:49:48 +00:00
thw a926ea1ae4 LICENSE change 2026-11-21 02:49:15 +01:00
thw b2684a2188 added license md file 2026-11-21 02:45:16 +01:00
thw b72898cd56 README update 2026-11-21 02:31:54 +01:00
thw 3bccab12fa feat(ui): Top-/Bottom-Bar zentralisieren, Poker & Blackjack überarbeiten & 1-Klasse-pro-Datei durchsetzen
- GothTopbar ausgelagert & entschlackt (ohne Spieltitel/Spielmenü-Button, Sprachwechsel in kombinierten Einstellungs-Dialog verschoben, zentriertes Level/XP-Badge)
- SolitaireBottomBar um dynamische Links-/Rechts-Overflow-Flügel, Pipe-Trenner, zentriertes HUD und sauberes Button-Cleanup erweitert
- Zentrale Vollbild-Statistikansicht (UnifiedStatsView) für alle Spiele inkl. Goldbeutel- und Varianten-Umschalter eingeführt
- Animiertes GothSwitch-Widget implementiert und optionale Button-Hover-Tooltips (Helvetica) an Settings gekoppelt
- Blackjack- & Poker-Tische auf Vollbild-Canvas umgebaut (kompakter Pot, dynamische Boxbreiten, spoilerfreie Poker-Kartenreferenz neben Spieler-Hand)
- Architektur-Cleanup (strikt 1 Klasse pro Datei: PokerHandsOverlay & SolitaireCard separiert) sowie AST-Prüfskripte für i18n und Multi-Class-Checks ergänzt
2026-11-21 02:20:50 +01:00
thw 4c29eda3c3 perf(ui): optimize Crostini/XWayland rendering and refactor Gothic UI layout
- Centralize compact GothTopbar title and 8-char/8-digit user badge within background safe-area

- Split solitaire_menu_chrome into MenuBodyCanvas, SolitaireModalDialog (with GIF support), and SolitaireBottomBar

- Remove general_table.jpg and render solitaire tables seamlessly over shared background cache

- Keep ResizingBG persistent across clear_window() to eliminate black-screen flickering

- Add C-accelerated PIL matte cleaning, lazy button state caching, pre-scaled card cache, and startup preloader
2026-11-19 22:50:58 +01:00
thw 6f614c8595 feat(ui): overhaul menus, stats & dialogs to custom canvas-based Gothic UI
- Add ui_typography.py and update game_constants.py for Old London typography and new image assets
- Upgrade AssetManager with downscaled 9-slice box rendering and PIL Old London text engine
- Convert ResizingBG to full-window Canvas with automatic horizontal/vertical background switching
- Add GothEntry and two-part GothDropdown with proportional arrow cap, mousewheel scrolling, and scroll indicators
- Update ImageButton with 3-slice side caps, frame-aware auto-width, and automatic icon stripping
- Refactor GothTopbar, LoginView, MainMenuView (hover zoom), StatisticsView, StatsBoardWidget, BotSetupWidget, and AudioSettingsDialog
- Migrate Blackjack, Poker, FreeCell, Klondike, and Spider menu/stats views plus BlackjackResultDialog to frameless canvas layouts
- Fix Crostini shelf icon matching via exact X11 WM_CLASS and absolute pixmap path
2026-11-17 22:31:02 +01:00
thw e1f4c35c35 fix(linux,crostini): fix OldLondon glyph clipping and prevent audio buffer underruns 2026-11-16 21:38:05 +01:00
thw 4caed5bc15 fix(blackjack,crostini): fix card fan TclError, add missing gold i18n keys & auto-setup Crostini shelf icon 2026-11-16 21:07:01 +01:00
thw 0abf754d86 vim un~ datei entfernt 2026-11-16 19:53:11 +01:00
thw 7ec2973c91 chore(db,build): modularize internal SQL, auto-rebuild DB & untrack build/user artifacts
- Split internal_base.sql into numbered modules under resources/code_res/sql/ and add missing BJ/Poker i18n keys
- Add rebuild_internal_db.py and integrate automatic DB rebuild into build.bat and build.sh
- Fix frozen PyInstaller path resolution for persistent user_data.db on Linux/ChromeOS
- Remove tracked dist/, build venv, and user_data.db from Git index and update .gitignore
2026-11-16 19:51:29 +01:00
thw 4c9b098fcb fix(blackjack): adjust oval table layout and fix text clipping 2026-11-16 00:22:24 +01:00
thw b91ba789d7 docs(readme): add Solitaire module READMEs & update main documentation
- Add dedicated README.md files for solitaire base framework, Klondike, FreeCell, and Spider Solitaire
- Update root README.md (DE/EN) with playable Solo modules, solver details, game icons, and framed table renderer
2026-11-15 23:16:56 +01:00
thw aad8a2f0d6 feat(solitaire): add Spider Solitaire, game tile icons & framed table background
- Add complete Spider Solitaire module (1/2/4 suits, strict 10-column deal rule & constructive deal generator)
- Render custom game icons on main menu cards with automatic badge cropping & rounded corners
- Add responsive general_table.jpg background renderer with frame-aware card insets across all Solitaire tables
- Rebuild internal_base.db with Spider Solitaire translations (DE/EN)
2026-11-15 23:06:29 +01:00
thw 3fc2e7f6e6 chore(git): enforce LF line endings via .gitattributes 2026-11-15 21:06:01 +01:00
thw 304e288987 feat(solitaire): add FreeCell, card flight animations, save/resume & deadlock handling
- Add complete FreeCell module (8 cascades, Supermove capacity, solver & 4 difficulty tiers)
- Add shared CardFlightAnimator for smooth 60fps card transitions, undo flights & snap-back
- Delay game timer start until first actual card/stock/hint interaction
- Add unlimited Undo to move 0, Undo All (Ctrl+Shift+Z), 3-cycle stock lock & deadlock modal
- Implement persistent auto-save/resume across restarts and clean shutdown on X / Ctrl+C
- Update playing card assets, responsive aspect-ratio scaling and i18n entries (DE/EN)
2026-11-15 21:03:27 +01:00
thw 6b37777464 removed the user_data.db 2026-11-15 01:40:35 +01:00
thw 6ef4067bf7 chore: untrack local release build scripts 2026-11-15 01:39:43 +01:00
391 changed files with 30972 additions and 6474 deletions

22
.gitattributes vendored Normal file
View File

@ -0,0 +1,22 @@
* text=auto eol=lf
*.py text eol=lf
*.sql text eol=lf
*.sh text eol=lf
*.json text eol=lf
*.md text eol=lf
*.bat text eol=crlf
*.cmd text eol=crlf
*.ps1 text eol=crlf
*.png binary
*.jpg binary
*.gif binary
*.ico binary
*.mp3 binary
*.wav binary
*.ogg binary
*.ttf binary
*.otf binary
*.db binary

182
.gitignore vendored
View File

@ -1,167 +1,21 @@
# Byte-compiled / optimized / DLL files # Lokale Spielstände & temporäre SQLite-Dateien
user_data.db
user_data.db-journal
user_data.db-wal
user_data.db-shm
*.db.tmp
# Build-Artefakte & virtuelle Build-Umgebungen
dist/
build/
*.spec
.venv/
venv/
.venv_build_*/
.env_build_*/
# Python-Cache
__pycache__/ __pycache__/
*.py[cod] *.py[cod]
*$py.class
# C extensions *.un~
*.so
# Distribution / packaging
bin/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# (Usually these files are written by a python script from a template before PyInstaller builds)
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translators note files
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since they are usually
# set by poetry or pipenv and could be unique to users
.python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to check in Pipfile.lock into version control.
# However, in some cases, you may wish to ignore it. See github.com/pypa/pipenv/issues/598
# pipenv.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to check poetry.lock into version control.
# This is especially true for binary packages to ensure reproducible builds.
# poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to check pdm.lock into version control.
# pdm.lock
.pdm.toml
# PEP 582; used by e.g. hatch, PDM
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak
venv.bak
.venv_build_linux/
.venv_build_macos/
.venv_build_win/
# Spyder project settings
.spyderproject
.spyderhistory
# Rope project settings
.ropeproject
# mkdocs documentation
./site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre.db
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm / VS Code / IDEs
.idea/
.vscode/
*.swp
*.swo
# OS generated files
zeit.txt
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
# Lokale Spielstand-Datenbank (wichtig, damit Spielstände nicht ins Git geraten)
user_data.db

140
README.md
View File

@ -16,8 +16,8 @@ Jedes Spiel arbeitet als vollständig gekapseltes Modul mit **eigener Erfahrungs
* **Flache 4-Kategorien-Navigation (keine verschachtelten Unterkategorien):** * **Flache 4-Kategorien-Navigation (keine verschachtelten Unterkategorien):**
* **Glück (`luck`):** Spiele mit eigenen Goldbeuteln, Tischeinsätzen, *Divine Punishment* und *The Devil's Deal* (**Blackjack**, **Texas Hold'em**). * **Glück (`luck`):** Spiele mit eigenen Goldbeuteln, Tischeinsätzen, *Divine Punishment* und *The Devil's Deal* (**Blackjack**, **Texas Hold'em**).
* **Solo (`solo`):** Klassische Patience-/Solitaire-Spiele ohne Gold-Zwang, mit eigenen Fortschritts- und Rückstufungsregeln (*Klondike*, *FreeCell*, *Spider Solitaire* – vorbereitet). * **Solo (`solo`):** Vollständig spielbare Patience-/Solitaire-Klassiker ohne Gold-Zwang, mit garantiert lösbaren Deals, 4 Schwierigkeitsgraden und eigenen XP-/Aufgaberegeln (**Klondike**, **FreeCell**, **Spider Solitaire**).
* **Gesellschaft - Offline (`party_offline`):** Lokale Gesellschaftsrunden gegen KI-Charaktere (in Vorbereitung). * **Gesellschaft - Offline (`party_offline`):** Lokale Gesellschaftsrunden gegen KI-Charaktere (z. B. *Rommé* – in Vorbereitung).
* **Online (`online`):** Mehrspieler-Tische & entfesselte Bots auf *Gottheit*-Niveau ohne Welpenschutz (in Vorbereitung). * **Online (`online`):** Mehrspieler-Tische & entfesselte Bots auf *Gottheit*-Niveau ohne Welpenschutz (in Vorbereitung).
* **Spielgebundenes Prestige- & Rangsystem:** * **Spielgebundenes Prestige- & Rangsystem:**
* **260 Ränge** (0–258 in römischen Stufen `I–V`, ab Rang 259 unendliche **Gottheit**-Stufen). * **260 Ränge** (0–258 in römischen Stufen `I–V`, ab Rang 259 unendliche **Gottheit**-Stufen).
@ -27,13 +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.
* **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)*.
* **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).
* **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 Spiel (`bot_configs`). * Frei konfigurierbare Gegner-Slots mit persistent gespeicherten Namen und KI-Stufen pro Tischspiel (`bot_configs`).
* **Gothic UI, 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, 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).
--- ---
@ -41,11 +48,13 @@ 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** | **Klondike** | Geplant | *Draw 1* & *Draw 3* (Stammdaten & Varianten-IDs vorbereitet) | — | | **Solo** | **Solitaire-Basis** | Aktiv | Gemeinsame Engine (`SolitaireCard` + `SolitaireBaseEngine`), `SolitaireBottomBar`, `CardFlightAnimator`, `SolitaireTableBgRenderer` & Auto-Save/Resume | [`games/solitaire/README.md`](games/solitaire/README.md) |
| **Solo** | **FreeCell** | Geplant | *Standard* (Stammdaten & Varianten-IDs vorbereitet) | — | | **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** | **Spider Solitaire** | Geplant | *1 Farbe*, *2 Farben*, *4 Farben* (Stammdaten & Varianten-IDs vorbereitet) | — | | **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) |
| **Gesellschaft** | **Rommé** | Geplant | Klassisches Offline-Gesellschaftsspiel gegen KI-Persönlichkeiten (`romme_icon.ico` vorbereitet) | — |
--- ---
@ -53,42 +62,54 @@ Jedes Spiel arbeitet als vollständig gekapseltes Modul mit **eigener Erfahrungs
~~~text ~~~text
the_goth_cardgame_collection/ the_goth_cardgame_collection/
├── .gitattributes # Erzwingt konsistente LF-Zeilenenden über Windows & Linux hinweg
├── 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
│ ├── deck.py # Deck- & Misch-Logik │ ├── deck.py # Deck- & Misch-Logik
│ ├── database.py # Kapselung aller SQLite-Zugriffe (ATTACH core + user_data.db) │ ├── database.py # Kapselung aller SQLite-Zugriffe (ATTACH core + user_data.db)
│ ├── progression.py # XP-Kurve, Prestige-Ränge, Chip-Skalierung & Divine Punishment │ ├── progression.py # XP-Kurve, Prestige-Ränge, Chip-Skalierung & Divine Punishment
│ ├── resource_manager.py # Dateipfad-Auflösung für Karten-Themes, Bilder & Sounds │ ├── resource_manager.py # Dateipfad-Auflösung für Karten-Themes, Spiel-Icons, Bilder & Sounds
│ └── sound_manager.py # Pygame-Mixer für Musik-Streams & SFX-Kanäle │ └── sound_manager.py # Pygame-Mixer für Musik-Streams & SFX-Kanäle
├── resources/ ├── resources/
│ ├── code_res/ │ ├── code_res/
│ │ ├── 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
│ ├── cards/default/ # Spielkarten-Grafiken & Kartenrücken
│ ├── fonts/ # Lokale TTF-Schriften (OldLondon.ttf, OldLondonAlternate.ttf) │ ├── fonts/ # Lokale TTF-Schriften (OldLondon.ttf, OldLondonAlternate.ttf)
│ ├── images/ # UI-Grafiken, Banner (title.jpg), Pokertisch, GIFs & game_icon.ico │ ├── images/ # UI-Grafiken, Rahmenboxen, Switch-Assets & Tischhintergründe
│ │ ├── cards/default/ # Spielkarten-Grafiken & Kartenrücken
│ │ └── 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, 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)
├── base/ # SolitaireCard, SolitaireBaseEngine, SolitaireBottomBar, Animator & Theme
├── klondike/ # Klondike (Draw 1 & Draw 3, 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)
~~~ ~~~
--- ---
@ -117,19 +138,24 @@ 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.
--- ---
--- ---
@ -146,8 +172,8 @@ Every game runs as a self-contained module with **strictly isolated progression
* **Flat 4-Category Navigation (no nested subcategories):** * **Flat 4-Category Navigation (no nested subcategories):**
* **Luck (`luck`):** High-consequence table games with dedicated Gold pouches, *Divine Punishment*, and *The Devil's Deal* (**Blackjack**, **Texas Hold'em**). * **Luck (`luck`):** High-consequence table games with dedicated Gold pouches, *Divine Punishment*, and *The Devil's Deal* (**Blackjack**, **Texas Hold'em**).
* **Solo (`solo`):** Skill-based solitaire classics without Gold requirements, governed by dedicated progression rules (*Klondike*, *FreeCell*, *Spider Solitaire* — prepared). * **Solo (`solo`):** Fully playable skill-based solitaire classics without Gold requirements, featuring guaranteed solvable deals, 4 difficulty tiers, and dedicated progression rules (**Klondike**, **FreeCell**, **Spider Solitaire**).
* **Party - Offline (`party_offline`):** Local parlor card games against AI personalities (planned). * **Party - Offline (`party_offline`):** Local parlor card games against AI personalities (e.g., *Rummy* — planned).
* **Online (`online`):** Multiplayer rooms & unleashed *Deity*-tier bots without hand-holding (planned). * **Online (`online`):** Multiplayer rooms & unleashed *Deity*-tier bots without hand-holding (planned).
* **Per-Game Prestige System:** * **Per-Game Prestige System:**
* **260 Prestige Ranks** (0–258 across Roman tiers `I–V`, followed by uncapped **Deity** levels from rank 259 onward), tracked independently per game (`game_progress`). * **260 Prestige Ranks** (0–258 across Roman tiers `I–V`, followed by uncapped **Deity** levels from rank 259 onward), tracked independently per game (`game_progress`).
@ -156,12 +182,20 @@ 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/`):**
* **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.
* **UX, Persistence & Fair Consequences:** Game timer waits until the first actual card/stock/hint interaction, auto-pauses when the window loses focus, saves every step with unlimited `Ctrl+Z` back to move $0$ plus `⟲ Reset Deal` (`Ctrl+Shift+Z`), and detects deadlocks automatically. Forfeiting an active deal deducts $40\,\%$ of a standard win's XP (protected by the *Creator Spirit V* floor).
* **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 game (`bot_configs`). * Configurable opponent seats with persistent names and AI levels per table game (`bot_configs`).
* **Gothic UI, 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, 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).
--- ---
@ -169,11 +203,13 @@ 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** | **Klondike** | Planned | *Draw 1* & *Draw 3* (core DB variants seeded) | — | | **Solo** | **Solitaire Core** | Active | Shared engine (`SolitaireCard` + `SolitaireBaseEngine`), `SolitaireBottomBar`, `CardFlightAnimator`, `SolitaireTableBgRenderer` & auto-save/resume | [`games/solitaire/README.md`](games/solitaire/README.md) |
| **Solo** | **FreeCell** | Planned | *Standard* (core DB variant seeded) | — | | **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** | **Spider Solitaire** | Planned | *1 Suit*, *2 Suits*, *4 Suits* (core DB variants seeded) | — | | **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) |
| **Party** | **Rummy** | Planned | Classic offline parlor card game against AI personalities (`romme_icon.ico` prepared) | — |
--- ---
@ -201,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.

View File

@ -1,122 +1,281 @@
@echo off @echo off
setlocal EnableDelayedExpansion setlocal EnableDelayedExpansion
REM ============================================================================= REM =============================================================================
REM The Goth Cardgame Collection - One-File Build Script (Windows + WSL) REM The Goth Cardgame Collection - Multi-Target Build Script (Windows + VBox VMs)
REM Output: dist\windows\TheGothCardgameCollection.exe REM Ablageort: build_scripts\build.bat
REM Usage: build_scripts\build.bat [--current | --all | --clean] REM Targets: --Win | --Unix | --OSX | --current | --all | --clean
REM ============================================================================= REM =============================================================================
REM --- Konfiguration fuer deine VirtualBox Linux-VM (--Unix) ---
set "UNIX_VM_NAME=UbuntuClient02"
set "UNIX_SSH_HOST=192.168.0.126"
set "UNIX_SSH_PORT=22"
set "UNIX_SSH_USER=kuro"
set "UNIX_REMOTE_DIR=~/the_goth_cardgame_collection_build"
REM --- Konfiguration fuer deine VirtualBox macOS-VM (--OSX) ---
set "OSX_VM_NAME=macOS"
set "OSX_SSH_HOST=192.168.0.158"
set "OSX_SSH_PORT=22"
set "OSX_SSH_USER=kuro"
set "OSX_REMOTE_DIR=~/the_goth_cardgame_collection_build"
set "SCRIPT_FILE=%~f0" set "SCRIPT_FILE=%~f0"
cd /d "%~dp0.." cd /d "%~dp0.."
set "PROJECT_ROOT=%CD%" set "PROJECT_ROOT=%CD%"
set "APP_NAME=TheGothCardgameCollection" set "APP_NAME=TheGothCardgameCollection"
set "MAIN_FILE=main.py"
set "RES_DIR=resources"
set "GAMES_DIR=games"
set "MODE=%~1"
if "%MODE%"=="" set "MODE=--current"
if /I "%MODE%"=="--clean" ( REM --- Parameter parsen (beliebig kombinierbar, case-insensitive) ---
if exist "build" rmdir /s /q "build" set "DO_WIN=0"
if exist ".venv_build_win" rmdir /s /q ".venv_build_win" set "DO_UNIX=0"
del /q "*.spec" 2>nul set "DO_OSX=0"
set "DO_CLEAN=0"
set "IS_ELEVATED=0"
set "RAW_ARGS="
:PARSE_ARGS
if "%~1"=="" goto :ARGS_DONE
if /I "%~1"=="--elevated" (
set "IS_ELEVATED=1"
shift
goto :PARSE_ARGS
)
set "RAW_ARGS=!RAW_ARGS! %~1"
if /I "%~1"=="--clean" set "DO_CLEAN=1"
if /I "%~1"=="--current" set "DO_WIN=1"
if /I "%~1"=="--win" set "DO_WIN=1"
if /I "%~1"=="--unix" set "DO_UNIX=1"
if /I "%~1"=="--linux" set "DO_UNIX=1"
if /I "%~1"=="--osx" set "DO_OSX=1"
if /I "%~1"=="--macos" set "DO_OSX=1"
if /I "%~1"=="--all" (
set "DO_WIN=1"
set "DO_UNIX=1"
set "DO_OSX=1"
)
shift
goto :PARSE_ARGS
:ARGS_DONE
if "%DO_CLEAN%"=="1" (
if exist "%PROJECT_ROOT%\build" rmdir /s /q "%PROJECT_ROOT%\build"
if exist "%PROJECT_ROOT%\.venv_build_win" rmdir /s /q "%PROJECT_ROOT%\.venv_build_win"
del /q "%PROJECT_ROOT%\*.spec" 2>nul
echo [OK] Temporaere Build-Dateien bereinigt. echo [OK] Temporaere Build-Dateien bereinigt.
exit /b 0 exit /b 0
) )
REM Nur wenn GAR KEIN Ziel angegeben wurde -> Standard --Win
if "%DO_WIN%"=="0" if "%DO_UNIX%"=="0" if "%DO_OSX%"=="0" (
set "DO_WIN=1"
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. ADMIN-RECHTE PRUEFEN (net session) REM 0. RECHTE- & ABHAENGIGKEITS-PRUEFUNG (nur fuer --Win noetig!)
REM ---------------------------------------------------- REM ----------------------------------------------------
set "IS_ADMIN=0" set "IS_ADMIN=0"
net session >nul 2>nul net session >nul 2>nul
if not errorlevel 1 set "IS_ADMIN=1" if not errorlevel 1 set "IS_ADMIN=1"
REM Kaputte Altlast-Venvs vorab bereinigen if exist "%PROJECT_ROOT%\.venv_build_win" (
if exist ".venv_build_win" ( if not exist "%PROJECT_ROOT%\.venv_build_win\Scripts\python.exe" rmdir /s /q "%PROJECT_ROOT%\.venv_build_win"
if not exist ".venv_build_win\Scripts\python.exe" rmdir /s /q ".venv_build_win"
) )
REM Vorhandenes Python ermitteln set "NEEDS_SETUP=0"
call :FIND_PYTHON if "%DO_WIN%"=="1" (
call :FIND_PYTHON
REM Pruefen, ob System-Installationen noetig sind (Python fehlt oder WSL-Distro fehlt bei --all) if "!WIN_PY!"=="" (
set "NEEDS_ADMIN=0" set "NEEDS_SETUP=1"
if "%WIN_PY%"=="" set "NEEDS_ADMIN=1" ) else (
!WIN_PY! -c "import pip, PIL, pygame, PyInstaller, tkinter" >nul 2>nul
set "WSL_DISTRO=" if errorlevel 1 set "NEEDS_SETUP=1"
if /I "%MODE%"=="--all" ( )
call :FIND_WSL_DISTRO
if "!WSL_DISTRO!"=="" set "NEEDS_ADMIN=1"
) )
REM Falls etwas auf Systemebene installiert werden muss und KEINE Admin-Rechte vorliegen -> UAC anfordern! if "%NEEDS_SETUP%"=="1" if "%IS_ADMIN%"=="0" (
if "%NEEDS_ADMIN%"=="1" if "%IS_ADMIN%"=="0" ( echo ====================================================
if /I "%~2"=="--elevated" ( echo [RECHTE-CHECK] Fehlende Windows-Pakete erkannt!
echo [ERROR] Administrator-Rechte wurden verweigert oder konnten nicht erlangt werden! echo Fordere Administrator-Rechte ueber Windows-UAC an...
echo Bitte starte die Konsole / PowerShell explizit "Als Administrator". echo ====================================================
if "%IS_ELEVATED%"=="1" (
echo [ERROR] Administrator-Freigabe fehlgeschlagen.
pause pause
exit /b 1 exit /b 1
) )
echo [ADMIN] Fehlende Systemkomponenten erkannt ^(Python oder WSL^). powershell -NoProfile -Command "Start-Process -FilePath 'cmd.exe' -ArgumentList '/k \"\"%SCRIPT_FILE%\" %RAW_ARGS% --elevated\"' -Verb RunAs"
echo Fordere Administrator-Rechte ueber Windows-UAC an...
powershell -NoProfile -Command "Start-Process -FilePath 'cmd.exe' -ArgumentList '/k \"\"%SCRIPT_FILE%\" %MODE% --elevated\"' -Verb RunAs"
exit /b 0 exit /b 0
) )
echo ==================================================== echo ====================================================
echo Starte Build fuer %APP_NAME% ^(Modus: %MODE% ^| Admin: %IS_ADMIN%^) echo Starte Build fuer %APP_NAME%
echo Ziele: Win=%DO_WIN% ^| Unix=%DO_UNIX% ^| OSX=%DO_OSX% ^(Admin: %IS_ADMIN%^)
echo ==================================================== echo ====================================================
REM Falls Python fehlte -> jetzt mit garantierten Admin-Rechten systemweit installieren if "%IS_ADMIN%"=="1" (
if "%WIN_PY%"=="" ( for /d %%G in ("C:\Python311\Lib\site-packages\~*") do rmdir /s /q "%%~G" 2>nul
echo [BOOTSTRAP] Installiere Python 3.11 via winget ^(Administrator^)... )
REM ----------------------------------------------------
REM STAMMDATENBANK VORAB FRISCH BAUEN (fuer Win + VM-Tarballs)
REM ----------------------------------------------------
set "DB_REBUILT=0"
call :FIND_PYTHON
if not "!WIN_PY!"=="" (
call :REBUILD_INTERNAL_DB
if errorlevel 1 (
echo [ERROR] Erstellung von internal_base.db fehlgeschlagen!
if "%IS_ELEVATED%"=="1" pause
exit /b 1
)
)
REM ====================================================
REM ZIEL 1: WINDOWS (--Win)
REM ====================================================
if "%DO_WIN%"=="1" (
echo.
echo ---^> [WIN] Baue Windows Single-File .exe...
if exist "%PROJECT_ROOT%\dist\windows" rmdir /s /q "%PROJECT_ROOT%\dist\windows"
call :BUILD_WIN_TARGET
if errorlevel 1 (
set "WIN_OK=0"
set "ANY_FAILED=1"
) else (
set "WIN_OK=1"
)
)
REM ====================================================
REM ZIEL 2: LINUX / UNIX VIA VIRTUALBOX VM (--Unix)
REM ====================================================
if "%DO_UNIX%"=="1" (
echo.
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
if errorlevel 1 (
set "UNIX_OK=0"
set "ANY_FAILED=1"
) else (
set "UNIX_OK=1"
)
)
REM ====================================================
REM ZIEL 3: MACOS / OSX VIA VIRTUALBOX VM (--OSX)
REM ====================================================
if "%DO_OSX%"=="1" (
echo.
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
if errorlevel 1 (
set "OSX_OK=0"
set "ANY_FAILED=1"
) else (
set "OSX_OK=1"
)
)
echo.
echo ====================================================
echo BUILD-ZUSAMMENFASSUNG ^(nur angeforderte Ziele^):
if "%DO_WIN%"=="1" (
if "!WIN_OK!"=="1" if exist "%PROJECT_ROOT%\dist\windows\%APP_NAME%.exe" (
echo [WIN] OK: dist\windows\%APP_NAME%.exe
) else (
echo [WIN] FEHLGESCHLAGEN!
)
)
if "%DO_UNIX%"=="1" (
if "!UNIX_OK!"=="1" if exist "%PROJECT_ROOT%\dist\linux\%APP_NAME%" (
echo [UNIX] OK: dist\linux\%APP_NAME% ^(+ %APP_NAME%_Linux.tar.gz^)
) else (
echo [UNIX] FEHLGESCHLAGEN! ^(VM "%UNIX_VM_NAME%" nicht erreichbar oder Build abgebrochen^)
)
)
if "%DO_OSX%"=="1" (
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^)
) else (
echo [OSX] FEHLGESCHLAGEN! ^(VM "%OSX_VM_NAME%" nicht erreichbar oder Build abgebrochen^)
)
)
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
endlocal
exit /b 0
REM ====================================================
REM HILFSROUTINEN
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 winget install -e --id Python.Python.3.11 --scope machine --accept-source-agreements --accept-package-agreements
for %%P in ( for %%P in ("%ProgramFiles%\Python311" "%LocalAppData%\Programs\Python\Python311" "C:\Python311") do (
"%ProgramFiles%\Python311"
"%LocalAppData%\Programs\Python\Python311"
"C:\Python311"
) do (
if exist "%%~P\python.exe" set "PATH=%%~P;%%~P\Scripts;!PATH!" if exist "%%~P\python.exe" set "PATH=%%~P;%%~P\Scripts;!PATH!"
) )
call :FIND_PYTHON call :FIND_PYTHON
) )
if "!WIN_PY!"=="" (
if "%WIN_PY%"=="" ( echo [ERROR] Python 3.11+ nicht gefunden!
echo [ERROR] Python 3.11+ konnte nicht gefunden oder installiert werden!
exit /b 1 exit /b 1
) )
REM ---------------------------------------------------- if "!DB_REBUILT!"=="0" (
REM TEIL 1: WINDOWS .EXE BAUEN call :REBUILD_INTERNAL_DB
REM ---------------------------------------------------- if errorlevel 1 exit /b 1
echo. )
echo ---^> [1] Baue Windows .exe mit %WIN_PY%...
REM Ohne Admin-Rechte & ausserhalb einer Venv installieren wir Pakete sauber mit --user !WIN_PY! -m pip --version >nul 2>nul
set "PIP_EXTRA=" if errorlevel 1 !WIN_PY! -m ensurepip --upgrade
if "%IS_ADMIN%"=="0" if "%USING_VENV%"=="0" set "PIP_EXTRA=--user"
%WIN_PY% -m pip install --upgrade pip !WIN_PY! -c "import PIL, pygame, PyInstaller" >nul 2>nul
%WIN_PY% -m pip install %PIP_EXTRA% --upgrade pillow pygame pyinstaller
if errorlevel 1 ( if errorlevel 1 (
echo [ERROR] Konnte Python-Pakete ^(PyInstaller/Pillow/Pygame^) nicht installieren! echo [BOOTSTRAP] Installiere Pillow, Pygame ^& PyInstaller...
exit /b 1 !WIN_PY! -m pip install --upgrade pip pillow pygame pyinstaller
if errorlevel 1 exit /b 1
) )
set "ICON_ARG=" set "ICON_ARG="
if exist "resources\images\game_icon.ico" set "ICON_ARG=--icon resources\images\game_icon.ico" if exist "%PROJECT_ROOT%\resources\images\game_icon.ico" (
set "ICON_ARG=--icon %PROJECT_ROOT%\resources\images\game_icon.ico"
)
%WIN_PY% -m PyInstaller ^ 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 ^ --noconfirm ^
--noconsole ^ --noconsole ^
--onefile ^ --onefile ^
--noupx ^
--clean ^ --clean ^
--distpath "dist\windows" ^ --distpath "%PROJECT_ROOT%\dist\windows" ^
--workpath "build\windows" ^ --workpath "%PROJECT_ROOT%\build\windows" ^
--specpath "build\windows" ^ --specpath "%PROJECT_ROOT%\build\windows" ^
%ICON_ARG% ^ !ICON_ARG! ^
--add-data "%RES_DIR%;%RES_DIR%" ^ !VER_ARG! ^
--add-data "%GAMES_DIR%;%GAMES_DIR%" ^ --add-data "%PROJECT_ROOT%\resources;resources" ^
--add-data "%PROJECT_ROOT%\games;games" ^
--collect-submodules games ^ --collect-submodules games ^
--collect-submodules controller ^ --collect-submodules controller ^
--collect-submodules models ^ --collect-submodules models ^
@ -128,94 +287,263 @@ if exist "resources\images\game_icon.ico" set "ICON_ARG=--icon resources\images\
--hidden-import sqlite3 ^ --hidden-import sqlite3 ^
--hidden-import PIL._tkinter_finder ^ --hidden-import PIL._tkinter_finder ^
--name "%APP_NAME%" ^ --name "%APP_NAME%" ^
"%MAIN_FILE%" "%PROJECT_ROOT%\main.py"
if errorlevel 1 ( if errorlevel 1 (
echo [ERROR] Windows-Build fehlgeschlagen! echo [ERROR] Windows-Build fehlgeschlagen!
exit /b 1 exit /b 1
) )
if exist "build\windows" rmdir /s /q "build\windows" if exist "%PROJECT_ROOT%\build\windows" rmdir /s /q "%PROJECT_ROOT%\build\windows"
echo [OK] Windows-Build fertig: dist\windows\%APP_NAME%.exe 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
REM ----------------------------------------------------
REM TEIL 2: LINUX EXECUTABLE VIA WSL (nur bei --all)
REM ----------------------------------------------------
if /I "%MODE%"=="--all" (
echo.
echo ---^> [2] Baue Linux Executable ^(via WSL^)...
call :FIND_WSL_DISTRO
if "!WSL_DISTRO!"=="" (
echo [BOOTSTRAP] Keine Linux-Distribution in WSL gefunden. Installiere Ubuntu ^(als Administrator^)...
wsl.exe --install -d Ubuntu --no-launch
call :FIND_WSL_DISTRO
if "!WSL_DISTRO!"=="" (
echo [HINWEIS] WSL/Ubuntu wurde vorbereitet. Windows erfordert einmalig einen System-Neustart,
echo bevor Linux-Builds in WSL ausgefuehrt werden koennen!
goto :SUMMARY
)
)
echo [WSL] Nutze Distribution: !WSL_DISTRO! ^(als root fuer Paket-Rechte^)
set "WSL_PROJ_PATH="
for /f "usebackq delims=" %%P in (`wsl.exe -d "!WSL_DISTRO!" -u root -- wslpath -a "%PROJECT_ROOT%" 2^>nul`) do (
set "WSL_PROJ_PATH=%%P"
)
if "!WSL_PROJ_PATH!"=="" (
echo [ERROR] Konnte Projektpfad "%PROJECT_ROOT%" in WSL nicht aufloesen.
exit /b 1
)
REM Fuehrt build.sh in WSL direkt als root (-u root) aus -> keine Passwort-Abfrage & volle apt-Rechte!
wsl.exe -d "!WSL_DISTRO!" -u root -- bash -lc "cd '!WSL_PROJ_PATH!' && sed -i 's/\r$//' build_scripts/build.sh && chmod +x build_scripts/build.sh && ./build_scripts/build.sh --current"
if errorlevel 1 (
echo [ERROR] Linux-Build in WSL fehlgeschlagen!
exit /b 1
)
) )
echo [OK] Windows-Build fertig: dist\windows\%APP_NAME%.exe
:SUMMARY
echo.
echo ====================================================
echo BUILD ABGESCHLOSSEN!
if exist "dist\windows\%APP_NAME%.exe" echo Windows: dist\windows\%APP_NAME%.exe
if exist "dist\linux\%APP_NAME%" echo Linux: dist\linux\%APP_NAME%
echo ====================================================
endlocal
exit /b 0 exit /b 0
:REBUILD_INTERNAL_DB
set "REBUILD_PY="
if exist "%PROJECT_ROOT%\build_scripts\rebuild_internal_db.py" (
set "REBUILD_PY=%PROJECT_ROOT%\build_scripts\rebuild_internal_db.py"
)
if exist "%PROJECT_ROOT%\rebuild_internal_db.py" (
set "REBUILD_PY=%PROJECT_ROOT%\rebuild_internal_db.py"
)
if not "!REBUILD_PY!"=="" (
if exist "%PROJECT_ROOT%\build_scripts\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"
) 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
REM ====================================================
REM HILFSROUTINEN
REM ====================================================
:FIND_PYTHON :FIND_PYTHON
set "WIN_PY=" set "WIN_PY="
set "USING_VENV=0" if exist "%PROJECT_ROOT%\.venv\Scripts\python.exe" (
if exist ".venv\Scripts\python.exe" ( "%PROJECT_ROOT%\.venv\Scripts\python.exe" -m pip --version >nul 2>nul && (
".venv\Scripts\python.exe" -m pip --version >nul 2>nul && ( set "WIN_PY=%PROJECT_ROOT%\.venv\Scripts\python.exe"
set "WIN_PY=.venv\Scripts\python.exe" exit /b 0
set "USING_VENV=1"
) )
) )
if "%WIN_PY%"=="" ( where python >nul 2>nul && (
where python >nul 2>nul && ( python -c "import sys, tkinter; sys.exit(0)" >nul 2>nul && (
python -c "import sys, tkinter; sys.exit(0)" >nul 2>nul && set "WIN_PY=python" set "WIN_PY=python"
exit /b 0
) )
) )
if "%WIN_PY%"=="" ( where py >nul 2>nul && (
where py >nul 2>nul && ( py -3 -c "import sys, tkinter; sys.exit(0)" >nul 2>nul && (
py -3 -c "import sys, tkinter; sys.exit(0)" >nul 2>nul && set "WIN_PY=py -3" set "WIN_PY=py -3"
exit /b 0
)
)
for %%D in ("C:\Python311\python.exe" "C:\Python312\python.exe" "%ProgramFiles%\Python311\python.exe" "%LocalAppData%\Programs\Python\Python311\python.exe") do (
if exist %%D (
%%D -c "import sys, tkinter; sys.exit(0)" >nul 2>nul && (
set "WIN_PY=%%D"
exit /b 0
)
) )
) )
exit /b 0 exit /b 0
:FIND_WSL_DISTRO :FIND_VBOX
set "WSL_DISTRO=" set "VBOX_MANAGE="
where wsl.exe >nul 2>nul where VBoxManage.exe >nul 2>nul && set "VBOX_MANAGE=VBoxManage.exe"
if errorlevel 1 exit /b 0 if "!VBOX_MANAGE!"=="" if exist "%ProgramFiles%\Oracle\VirtualBox\VBoxManage.exe" (
for /f "usebackq delims=" %%L in (`powershell -NoProfile -Command "$d = (wsl.exe -l -q 2>$null) -replace '\x00','' | ForEach-Object { $_.Trim() } | Where-Object { $_ -and $_ -notmatch '^docker-desktop' }; if ($d) { $d | Select-Object -First 1 }"`) do ( set "VBOX_MANAGE=%ProgramFiles%\Oracle\VirtualBox\VBoxManage.exe"
if "!WSL_DISTRO!"=="" set "WSL_DISTRO=%%L"
) )
if "!VBOX_MANAGE!"=="" if exist "D:\Program Files\Oracle\VirtualBox\VBoxManage.exe" (
set "VBOX_MANAGE=D:\Program Files\Oracle\VirtualBox\VBoxManage.exe"
)
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
call :FIND_VBOX
if "!VBOX_MANAGE!"=="" (
echo [ERROR] VBoxManage.exe nicht gefunden - Linux-VM-Build fehlgeschlagen!
exit /b 1
)
"!VBOX_MANAGE!" showvminfo "%UNIX_VM_NAME%" >nul 2>nul
if errorlevel 1 (
echo [ERROR] VirtualBox-VM "%UNIX_VM_NAME%" nicht gefunden!
call :PRINT_AVAILABLE_VMS
exit /b 1
)
set "UNIX_VM_WAS_RUNNING=0"
"!VBOX_MANAGE!" list runningvms | findstr /I "\"%UNIX_VM_NAME%\"" >nul 2>nul
if not errorlevel 1 set "UNIX_VM_WAS_RUNNING=1"
if "!UNIX_VM_WAS_RUNNING!"=="0" (
echo [UNIX-VM] Starte VirtualBox-VM "%UNIX_VM_NAME%" im Headless-Modus...
"!VBOX_MANAGE!" startvm "%UNIX_VM_NAME%" --type headless
if errorlevel 1 (
echo [ERROR] Konnte VM "%UNIX_VM_NAME%" nicht starten!
exit /b 1
)
)
echo [UNIX-VM] Warte auf SSH-Verbindung ^(%UNIX_SSH_USER%@%UNIX_SSH_HOST%:%UNIX_SSH_PORT%^)...
set "UNIX_SSH_READY=0"
for /L %%I in (1,1,30) do (
if "!UNIX_SSH_READY!"=="0" (
ssh -p %UNIX_SSH_PORT% -o BatchMode=yes -o ConnectTimeout=3 -o StrictHostKeyChecking=accept-new %UNIX_SSH_USER%@%UNIX_SSH_HOST% "echo ready" >nul 2>nul
if not errorlevel 1 (
set "UNIX_SSH_READY=1"
) else (
timeout /t 3 /nobreak >nul
)
)
)
if "!UNIX_SSH_READY!"=="0" (
echo [ERROR] Keine passwortlose SSH-Verbindung zu %UNIX_SSH_USER%@%UNIX_SSH_HOST%:%UNIX_SSH_PORT% moeglich.
if "!UNIX_VM_WAS_RUNNING!"=="0" "!VBOX_MANAGE!" controlvm "%UNIX_VM_NAME%" acpipowerbutton >nul 2>nul
exit /b 1
)
echo [UNIX-VM] Aktualisiere Projektquellen in "%UNIX_VM_NAME%"...
set "TMP_TAR_UNIX=%TEMP%\goth_unix_src.tar.gz"
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%" .
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 -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
set "SCP_ERR=!ERRORLEVEL!"
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...
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 (
echo [ERROR] Linux-Build in der VM fehlgeschlagen!
if "!UNIX_VM_WAS_RUNNING!"=="0" "!VBOX_MANAGE!" controlvm "%UNIX_VM_NAME%" acpipowerbutton >nul 2>nul
exit /b 1
)
mkdir "%PROJECT_ROOT%\dist\linux" 2>nul
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"
if errorlevel 1 (
echo [ERROR] Download des Linux-Artefakts fehlgeschlagen!
exit /b 1
)
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" (
echo [UNIX-VM] Fahre Linux-VM wieder sauber herunter...
"!VBOX_MANAGE!" controlvm "%UNIX_VM_NAME%" acpipowerbutton >nul 2>nul
)
echo [OK] Linux-Build fertig unter: dist\linux\
exit /b 0
:RUN_OSX_VM_BUILD
call :FIND_VBOX
if "!VBOX_MANAGE!"=="" (
echo [ERROR] VBoxManage.exe nicht gefunden - macOS-VM-Build fehlgeschlagen!
exit /b 1
)
"!VBOX_MANAGE!" showvminfo "%OSX_VM_NAME%" >nul 2>nul
if errorlevel 1 (
echo [ERROR] VirtualBox-VM "%OSX_VM_NAME%" nicht gefunden!
call :PRINT_AVAILABLE_VMS
exit /b 1
)
set "VM_WAS_RUNNING=0"
"!VBOX_MANAGE!" list runningvms | findstr /I "\"%OSX_VM_NAME%\"" >nul 2>nul
if not errorlevel 1 set "VM_WAS_RUNNING=1"
if "!VM_WAS_RUNNING!"=="0" (
echo [OSX-VM] Starte VirtualBox-VM "%OSX_VM_NAME%" im Headless-Modus...
"!VBOX_MANAGE!" startvm "%OSX_VM_NAME%" --type headless
if errorlevel 1 (
echo [ERROR] Konnte VM "%OSX_VM_NAME%" nicht starten!
exit /b 1
)
)
echo [OSX-VM] Warte auf SSH-Verbindung ^(%OSX_SSH_USER%@%OSX_SSH_HOST%:%OSX_SSH_PORT%^)...
set "SSH_READY=0"
for /L %%I in (1,1,30) do (
if "!SSH_READY!"=="0" (
ssh -p %OSX_SSH_PORT% -o BatchMode=yes -o ConnectTimeout=3 -o StrictHostKeyChecking=accept-new %OSX_SSH_USER%@%OSX_SSH_HOST% "echo ready" >nul 2>nul
if not errorlevel 1 (
set "SSH_READY=1"
) else (
timeout /t 4 /nobreak >nul
)
)
)
if "!SSH_READY!"=="0" (
echo [ERROR] Keine passwortlose SSH-Verbindung zu %OSX_SSH_USER%@%OSX_SSH_HOST%:%OSX_SSH_PORT% moeglich.
if "!VM_WAS_RUNNING!"=="0" "!VBOX_MANAGE!" controlvm "%OSX_VM_NAME%" acpipowerbutton >nul 2>nul
exit /b 1
)
echo [OSX-VM] Aktualisiere Projektquellen in der macOS-VM ^(.venv_build_macos bleibt gecached!^)...
set "TMP_TAR=%TEMP%\goth_osx_src.tar.gz"
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%" .
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 -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
set "SCP_OSX_ERR=!ERRORLEVEL!"
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...
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 (
echo [ERROR] macOS-Build in der VM fehlgeschlagen!
if "!VM_WAS_RUNNING!"=="0" "!VBOX_MANAGE!" controlvm "%OSX_VM_NAME%" acpipowerbutton >nul 2>nul
exit /b 1
)
mkdir "%PROJECT_ROOT%\dist\macos" 2>nul
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/%APP_NAME%_macOS.tar.gz "%PROJECT_ROOT%\dist\macos\%APP_NAME%_macOS.tar.gz"
if errorlevel 1 (
echo [ERROR] Download des macOS-Artefakts fehlgeschlagen!
exit /b 1
)
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" (
echo [OSX-VM] Fahre macOS-VM wieder sauber herunter...
"!VBOX_MANAGE!" controlvm "%OSX_VM_NAME%" acpipowerbutton >nul 2>nul
)
echo [OK] macOS-Build fertig unter: dist\macos\
exit /b 0 exit /b 0

View File

@ -1,10 +1,8 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# ============================================================================= # Lokales Build-Skript (nur Linux & Windows via Wine)
# The Goth Cardgame Collection - One-File Build Script (Linux / ChromeOS / macOS) # Ablageort: build_scripts/build.sh
# Output: dist/<os>/TheGothCardgameCollection # Targets: --Win | --Unix | --current | --all | --clean
# Usage: ./build_scripts/build.sh [--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]}")"
@ -12,72 +10,74 @@ PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "${PROJECT_ROOT}" cd "${PROJECT_ROOT}"
APP_NAME="TheGothCardgameCollection" APP_NAME="TheGothCardgameCollection"
MAIN_FILE="main.py" ICON_ICO="${PROJECT_ROOT}/resources/images/game_icon.ico"
RES_DIR="resources" VERSION_TXT="${PROJECT_ROOT}/build_scripts/version_info.txt"
GAMES_DIR="games"
ICON_FILE="resources/images/game_icon.ico"
MODE="${1:---current}"
if [ "$MODE" = "--clean" ]; then
echo "🧹 Räume temporäre Build-Ordner auf..."
rm -rf build .venv_build_* *.spec
exit 0
fi
UNAME_OUT="$(uname -s)" UNAME_OUT="$(uname -s)"
case "${UNAME_OUT}" in case "${UNAME_OUT}" in
Linux*) OS_NAME="linux" ;; Linux*) ;;
Darwin*) OS_NAME="macos" ;; *) echo "❌ Dieses Skript unterstützt nur Linux-Systeme (gefunden: ${UNAME_OUT})."; exit 1 ;;
*) echo "❌ Unbekanntes Unix-System: ${UNAME_OUT}"; exit 1 ;;
esac esac
# ---------------------------------------------------- DO_WIN=0
# 0. ROOT / SUDO RECHTE-CHECK FÜR SYSTEM-INSTALLATIONEN DO_UNIX=0
# ---------------------------------------------------- DO_CLEAN=0
NEEDS_SYS_INSTALL=0 ORIG_ARGS=("$@")
if ! command -v python3 &>/dev/null || ! python3 -c "import tkinter" &>/dev/null; then
NEEDS_SYS_INSTALL=1 for arg in "$@"; do
fi arg_lc="$(printf '%s' "$arg" | tr '[:upper:]' '[:lower:]')"
if [ "$MODE" = "--all" ] && [ "$OS_NAME" = "linux" ] && ! command -v wine &>/dev/null; then case "$arg_lc" in
NEEDS_SYS_INSTALL=1 --clean) DO_CLEAN=1 ;;
--win|--windows) DO_WIN=1 ;;
--unix|--linux) DO_UNIX=1 ;;
--current) DO_UNIX=1 ;;
--all) DO_WIN=1; DO_UNIX=1 ;;
*)
echo "❌ Unbekannte Option: $arg (Erlaubt: --Win | --Unix | --current | --all | --clean)"
exit 1
;;
esac
done
if [ "$DO_CLEAN" -eq 1 ]; then
rm -rf "${PROJECT_ROOT}/build" "${PROJECT_ROOT}"/.venv_build_* "${PROJECT_ROOT}"/*.spec
echo "🧹 Temporäre Build-Ordner bereinigt."
exit 0
fi fi
if [ "$OS_NAME" = "linux" ] && [ "$NEEDS_SYS_INSTALL" -eq 1 ]; then # Standardziel ohne Parameter: nativer Linux-Build
if [ "${EUID:-$(id -u)}" -ne 0 ]; then if [ "$DO_WIN" -eq 0 ] && [ "$DO_UNIX" -eq 0 ]; then
echo "🔒 Es fehlen Systempakete (z.B. python3-tk oder wine), für deren Installation Root-Rechte nötig sind." DO_UNIX=1
if command -v sudo &>/dev/null; then fi
echo "🔑 Fordere Root-Rechte via sudo an und starte Skript neu..."
exec sudo -E bash "$SCRIPT_PATH" "$@" # Root/Sudo Check unter Linux falls Systempakete fehlen
else NEEDS_SYS_INSTALL=0
echo "❌ FEHLER: Keine Root-Rechte (EUID != 0) und 'sudo' ist nicht installiert!" if [ "$DO_UNIX" -eq 1 ]; then
echo " Bitte führe das Skript als root aus: su -c '$SCRIPT_PATH $MODE'" if ! command -v python3 &>/dev/null || ! python3 -c "import tkinter" &>/dev/null || ! python3 -m pip --version &>/dev/null; then
exit 1 NEEDS_SYS_INSTALL=1
fi
fi fi
fi fi
if [ "$DO_WIN" -eq 1 ] && ! command -v wine &>/dev/null; then
NEEDS_SYS_INSTALL=1
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
# Echten User ermitteln (wichtig, falls Skript via sudo/root läuft, damit Wine & Dateirechte stimmen!)
if [ "${EUID:-$(id -u)}" -eq 0 ] && [ -n "${SUDO_USER:-}" ]; then if [ "${EUID:-$(id -u)}" -eq 0 ] && [ -n "${SUDO_USER:-}" ]; then
REAL_USER="$SUDO_USER" REAL_USER="$SUDO_USER"
REAL_HOME="$(getent passwd "$SUDO_USER" | cut -d: -f6)" REAL_HOME="$(getent passwd "$SUDO_USER" | cut -d: -f6)"
WINE_RUNNER=(sudo -u "$REAL_USER" HOME="$REAL_HOME") USER_RUNNER=(sudo -u "$REAL_USER" HOME="$REAL_HOME")
else else
REAL_USER="$(whoami)" REAL_USER="$(whoami)"
REAL_HOME="$HOME" REAL_HOME="$HOME"
WINE_RUNNER=() USER_RUNNER=()
fi fi
echo "===================================================="
echo " 🦇 Starte Build für $APP_NAME (OS: $OS_NAME | Modus: $MODE)"
echo "===================================================="
# ----------------------------------------------------
# SYSTEMPAKETE INSTALLIEREN (läuft garantiert als root!)
# ----------------------------------------------------
install_linux_pkgs() { install_linux_pkgs() {
if command -v apt-get &>/dev/null; then if command -v apt-get &>/dev/null; then
apt-get update -qq apt-get update -qq && apt-get install -y "$@"
apt-get install -y "$@"
elif command -v dnf &>/dev/null; then elif command -v dnf &>/dev/null; then
dnf install -y "$@" dnf install -y "$@"
elif command -v yum &>/dev/null; then elif command -v yum &>/dev/null; then
@ -86,181 +86,148 @@ install_linux_pkgs() {
zypper --non-interactive install "$@" zypper --non-interactive install "$@"
elif command -v pacman &>/dev/null; then elif command -v pacman &>/dev/null; then
pacman -Sy --noconfirm --needed "$@" pacman -Sy --noconfirm --needed "$@"
else
echo "❌ Kein unterstützter Paketmanager (apt/dnf/yum/zypper/pacman) gefunden!"
exit 1
fi fi
} }
if [ "$OS_NAME" = "linux" ] && { ! command -v python3 &>/dev/null || ! python3 -c "import tkinter" &>/dev/null; }; then rebuild_internal_db_if_present() {
echo "⚙️ Installiere fehlende Python-/Tkinter-Systempakete..." local py_bin="$1"
if command -v apt-get &>/dev/null; then local rebuild_py=""
install_linux_pkgs python3 python3-pip python3-venv python3-tk wget if [ -f "${PROJECT_ROOT}/rebuild_internal_db.py" ]; then
elif command -v dnf &>/dev/null || command -v yum &>/dev/null; then rebuild_py="${PROJECT_ROOT}/rebuild_internal_db.py"
install_linux_pkgs python3 python3-pip python3-tkinter wget elif [ -f "${PROJECT_ROOT}/build_scripts/rebuild_internal_db.py" ]; then
elif command -v zypper &>/dev/null; then rebuild_py="${PROJECT_ROOT}/build_scripts/rebuild_internal_db.py"
install_linux_pkgs python3 python3-pip python3-tk wget
elif command -v pacman &>/dev/null; then
install_linux_pkgs python python-pip tk wget
fi fi
elif [ "$OS_NAME" = "macos" ] && { ! command -v python3 &>/dev/null || ! python3 -c "import tkinter" &>/dev/null; }; then
if [ "${EUID:-$(id -u)}" -eq 0 ]; then if [ -n "$rebuild_py" ] && [ -d "${PROJECT_ROOT}/resources/code_res/sql" ]; then
echo "❌ Unter macOS darf Homebrew nicht als root ausgeführt werden. Bitte ohne sudo starten." echo "---> [DB] Aktualisiere internal_base.db aus modularen SQL-Dateien..."
exit 1 "${USER_RUNNER[@]}" "$py_bin" "$rebuild_py"
fi fi
if command -v brew &>/dev/null; then }
brew install python@3.11 python-tk@3.11
else
echo "❌ Python3/Tkinter fehlt und Homebrew ist nicht installiert."
exit 1
fi
fi
# ---------------------------------------------------- DB_REBUILT=0
# TEIL 1: LINUX / MACOS EXECUTABLE BAUEN
# ----------------------------------------------------
echo ""
echo "---> [1] Baue ${OS_NAME} Executable..."
# Defekte Venvs automatisch bereinigen # 1. NATIVER LINUX BUILD (--Unix)
for VDIR in ".venv_build_${OS_NAME}" ".venv" "venv"; do if [ "$DO_UNIX" -eq 1 ]; then
if [ -d "$VDIR" ] && [ ! -x "$VDIR/bin/python3" ]; then echo "---> [UNIX] Baue Linux Executable..."
echo "🧹 Entferne defektes Venv: $VDIR" if [ "$NEEDS_SYS_INSTALL" -eq 1 ]; then
rm -rf "$VDIR"
fi
done
if [ -x ".venv/bin/python3" ]; then
LINUX_PY=".venv/bin/python3"
elif [ -x "venv/bin/python3" ]; then
LINUX_PY="venv/bin/python3"
else
LINUX_PY="python3"
fi
# Falls wir nicht root sind und kein Venv nutzen, pip mit --user ausführen, damit es keine Permission-Errors gibt
PIP_USER_FLAG=()
if [ "$LINUX_PY" = "python3" ] && [ "${EUID:-$(id -u)}" -ne 0 ]; then
PIP_USER_FLAG=(--user)
fi
$LINUX_PY -m pip install "${PIP_USER_FLAG[@]}" --upgrade pillow pygame pyinstaller --break-system-packages 2>/dev/null \
|| $LINUX_PY -m pip install "${PIP_USER_FLAG[@]}" --upgrade pillow pygame pyinstaller
ICON_ARG=()
[ -f "$ICON_FILE" ] && ICON_ARG=(--icon "$ICON_FILE")
$LINUX_PY -m PyInstaller \
--noconfirm \
--noconsole \
--onefile \
--clean \
--distpath "dist/${OS_NAME}" \
--workpath "build/${OS_NAME}" \
--specpath "build/${OS_NAME}" \
"${ICON_ARG[@]}" \
--add-data "${RES_DIR}:${RES_DIR}" \
--add-data "${GAMES_DIR}:${GAMES_DIR}" \
--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}" \
"$MAIN_FILE"
chmod +x "dist/${OS_NAME}/${APP_NAME}"
rm -rf "build/${OS_NAME}"
echo "✔ ${OS_NAME}-Build fertig: dist/${OS_NAME}/${APP_NAME}"
# ----------------------------------------------------
# TEIL 2: WINDOWS .EXE BAUEN VIA WINE (nur bei --all unter Linux)
# ----------------------------------------------------
if [ "$MODE" = "--all" ] && [ "$OS_NAME" = "linux" ]; then
echo ""
echo "---> [2] Baue Windows .exe (via Wine)..."
if ! command -v wine &>/dev/null; then
echo "⚙️ Installiere 'wine' und 'wget' (Root-Rechte bereits geprüft)..."
if command -v apt-get &>/dev/null; then if command -v apt-get &>/dev/null; then
dpkg --add-architecture amd64 2>/dev/null || true install_linux_pkgs python3 python3-pip python3-venv python3-tk wget
install_linux_pkgs wine wget elif command -v dnf &>/dev/null || command -v yum &>/dev/null; then
else install_linux_pkgs python3 python3-pip python3-tkinter wget
install_linux_pkgs wine wget elif command -v zypper &>/dev/null; then
install_linux_pkgs python3 python3-pip python3-tk wget
elif command -v pacman &>/dev/null; then
install_linux_pkgs python python-pip tk wget
fi fi
fi fi
for VDIR in "${PROJECT_ROOT}/.venv_build_linux" "${PROJECT_ROOT}/.venv" "${PROJECT_ROOT}/venv"; do
if [ -d "$VDIR" ] && [ ! -x "$VDIR/bin/python3" ]; then rm -rf "$VDIR"; fi
done
LINUX_PY="python3"
[ -x "${PROJECT_ROOT}/.venv/bin/python3" ] && LINUX_PY="${PROJECT_ROOT}/.venv/bin/python3"
if [ "$DB_REBUILT" -eq 0 ]; then
rebuild_internal_db_if_present "$LINUX_PY"
DB_REBUILT=1
fi
if ! "$LINUX_PY" -c "import PIL, pygame, PyInstaller" &>/dev/null; then
PIP_USER_FLAG=()
[ "$LINUX_PY" = "python3" ] && [ "${EUID:-$(id -u)}" -ne 0 ] && PIP_USER_FLAG=(--user)
"$LINUX_PY" -m pip install "${PIP_USER_FLAG[@]}" --upgrade pillow pygame pyinstaller --break-system-packages 2>/dev/null \
|| "$LINUX_PY" -m pip install "${PIP_USER_FLAG[@]}" --upgrade pillow pygame pyinstaller
fi
ICON_ARG=()
[ -f "$ICON_ICO" ] && ICON_ARG=(--icon "$ICON_ICO")
"${USER_RUNNER[@]}" "$LINUX_PY" -m PyInstaller \
--noconfirm --noconsole --onefile --noupx --clean \
--distpath "${PROJECT_ROOT}/dist/linux" \
--workpath "${PROJECT_ROOT}/build/linux" \
--specpath "${PROJECT_ROOT}/build/linux" \
"${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/linux/${APP_NAME}"
rm -rf "${PROJECT_ROOT}/build/linux"
echo "✔ Linux-Build fertig: dist/linux/${APP_NAME}"
fi
# 2. WINDOWS BUILD VIA WINE (--Win)
if [ "$DO_WIN" -eq 1 ]; then
echo "---> [WIN] Baue Windows .exe (via Wine)..."
if ! command -v wine &>/dev/null; then if ! command -v wine &>/dev/null; then
echo "❌ 'wine' konnte nicht installiert werden!" command -v apt-get &>/dev/null && dpkg --add-architecture amd64 2>/dev/null || true
exit 1 install_linux_pkgs wine wget curl
fi
if [ "$DB_REBUILT" -eq 0 ] && command -v python3 &>/dev/null; then
rebuild_internal_db_if_present "python3"
DB_REBUILT=1
fi fi
WINE_DRIVE_C="${REAL_HOME}/.wine/drive_c" WINE_DRIVE_C="${REAL_HOME}/.wine/drive_c"
WINE_PY=$(find "$WINE_DRIVE_C" -iname "python.exe" 2>/dev/null | grep -i "Python3" | head -n 1 || true) WINE_PY=$(find "$WINE_DRIVE_C" -iname "python.exe" 2>/dev/null | grep -i "Python3" | head -n 1 || true)
if [ -z "$WINE_PY" ]; then if [ -z "$WINE_PY" ]; then
echo "⚙️ Windows-Python in Wine (${WINE_DRIVE_C}) nicht gefunden. Installiere Python 3.11.9 automatisch..."
INSTALLER="/tmp/python-3.11.9-amd64.exe" INSTALLER="/tmp/python-3.11.9-amd64.exe"
if [ ! -f "$INSTALLER" ]; then [ ! -f "$INSTALLER" ] && curl -fsSL "https://www.python.org/ftp/python/3.11.9/python-3.11.9-amd64.exe" -o "$INSTALLER"
wget -O "$INSTALLER" https://www.python.org/ftp/python/3.11.9/python-3.11.9-amd64.exe "${USER_RUNNER[@]}" wine "$INSTALLER" /quiet InstallAllUsers=1 PrependPath=1 Include_test=0
fi "${USER_RUNNER[@]}" wineserver -w || true
"${WINE_RUNNER[@]}" wine "$INSTALLER" /quiet InstallAllUsers=1 PrependPath=1 Include_test=0
"${WINE_RUNNER[@]}" wineserver -w || true
rm -f "$INSTALLER" rm -f "$INSTALLER"
WINE_PY=$(find "$WINE_DRIVE_C" -iname "python.exe" 2>/dev/null | grep -i "Python3" | head -n 1 || true) WINE_PY=$(find "$WINE_DRIVE_C" -iname "python.exe" 2>/dev/null | grep -i "Python3" | head -n 1 || true)
fi fi
if [ -z "$WINE_PY" ]; then WIN_ROOT="$("${USER_RUNNER[@]}" winepath -w "${PROJECT_ROOT}")"
echo "❌ Konnte python.exe in ${WINE_DRIVE_C} nicht finden!" if [ "$DB_REBUILT" -eq 0 ]; then
exit 1 if [ -f "${PROJECT_ROOT}/rebuild_internal_db.py" ]; then
echo "---> [DB] Aktualisiere internal_base.db via Wine-Python..."
"${USER_RUNNER[@]}" wine "$WINE_PY" "${WIN_ROOT}\\rebuild_internal_db.py"
elif [ -f "${PROJECT_ROOT}/build_scripts/rebuild_internal_db.py" ]; then
echo "---> [DB] Aktualisiere internal_base.db via Wine-Python..."
"${USER_RUNNER[@]}" wine "$WINE_PY" "${WIN_ROOT}\\build_scripts\\rebuild_internal_db.py"
fi
DB_REBUILT=1
fi fi
echo "✔ Nutze Wine-Python: $WINE_PY" 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_RUNNER[@]}" wine "$WINE_PY" -m pip install --upgrade pip pillow pygame pyinstaller WINE_ICON_ARG=()
[ -f "$ICON_ICO" ] && WINE_ICON_ARG=(--icon "${WIN_ROOT}\\resources\\images\\game_icon.ico")
"${WINE_RUNNER[@]}" wine "$WINE_PY" -m PyInstaller \ WINE_VER_ARG=()
--noconfirm \ [ -f "$VERSION_TXT" ] && WINE_VER_ARG=(--version-file "${WIN_ROOT}\\build_scripts\\version_info.txt")
--noconsole \
--onefile \
--clean \
--distpath "dist/windows" \
--workpath "build/windows" \
--specpath "build/windows" \
"${ICON_ARG[@]}" \
--add-data "${RES_DIR};${RES_DIR}" \
--add-data "${GAMES_DIR};${GAMES_DIR}" \
--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}" \
"$MAIN_FILE"
rm -rf "build/windows" "${USER_RUNNER[@]}" wine "$WINE_PY" -m PyInstaller \
--noconfirm --noconsole --onefile --noupx --clean \
--distpath "${WIN_ROOT}\\dist\\windows" \
--workpath "${WIN_ROOT}\\build\\windows" \
--specpath "${WIN_ROOT}\\build\\windows" \
"${WINE_ICON_ARG[@]}" \
"${WINE_VER_ARG[@]}" \
--add-data "${WIN_ROOT}\\resources;resources" \
--add-data "${WIN_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}" "${WIN_ROOT}\\main.py"
rm -rf "${PROJECT_ROOT}/build/windows"
echo "✔ Windows-Build fertig: dist/windows/${APP_NAME}.exe" echo "✔ Windows-Build fertig: dist/windows/${APP_NAME}.exe"
fi fi
# Falls via sudo gestartet, Besitzrechte von dist/ wieder auf den normalen User übertragen
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" dist/ 2>/dev/null || true chown -R "$SUDO_USER:$SUDO_USER" "${PROJECT_ROOT}/dist" 2>/dev/null || true
fi fi
echo ""
echo "===================================================="
echo " ✅ BUILD ERFOLGREICH ABGESCHLOSSEN!"
[ -f "dist/${OS_NAME}/${APP_NAME}" ] && echo " 🐧 ${OS_NAME}-Version: dist/${OS_NAME}/${APP_NAME}"
[ -f "dist/windows/${APP_NAME}.exe" ] && echo " 🪟 Windows-Version: dist/windows/${APP_NAME}.exe"
echo "===================================================="

View File

@ -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

View File

@ -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 ""
}
}
}

View File

@ -0,0 +1,134 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
rebuild_internal_db.py
Baut resources/code_res/internal_base.db frisch aus den aufgeteilten SQL-Dateien
unter resources/code_res/sql/ zusammen (plattformunabhängig ohne externes sqlite3-Binary).
"""
from __future__ import annotations
import argparse
import sqlite3
import sys
from pathlib import Path
def _detect_project_root() -> Path:
here = Path(__file__).resolve().parent
for candidate in (here, here.parent, here.parent.parent):
if (candidate / "resources" / "code_res").is_dir():
return candidate
return Path.cwd()
def build_database(sql_dir: Path, db_path: Path, export_merged: Path | None = None) -> int:
if not sql_dir.is_dir():
print(f"[FEHLER] SQL-Verzeichnis nicht gefunden: {sql_dir}", file=sys.stderr)
return 1
sql_files = sorted(sql_dir.glob("*.sql"))
if not sql_files:
print(f"[FEHLER] Keine .sql-Dateien in {sql_dir} gefunden!", file=sys.stderr)
return 1
db_path.parent.mkdir(parents=True, exist_ok=True)
tmp_db_path = db_path.with_suffix(".db.tmp")
if tmp_db_path.exists():
tmp_db_path.unlink()
merged_chunks: list[str] = [
"-- Automatisch zusammengeführt durch rebuild_internal_db.py",
"PRAGMA foreign_keys = ON;",
"BEGIN TRANSACTION;",
"",
]
try:
conn = sqlite3.connect(tmp_db_path)
try:
conn.execute("PRAGMA foreign_keys = ON;")
for sf in sql_files:
# utf-8-sig fängt auch versehentliche UTF-8-BOMs unter Windows sauber ab
raw_sql = sf.read_text(encoding="utf-8-sig")
print(f" -> Lade {sf.name} ...")
conn.executescript(raw_sql)
merged_chunks.append(f"-- >>> {sf.name} <<<\n{raw_sql.strip()}\n")
# Integritäts- & Sprach-Paritätsprüfung (DE vs. EN)
cur = conn.cursor()
cur.execute("SELECT COUNT(*) FROM game_variants;")
variant_count = cur.fetchone()[0]
cur.execute("SELECT COUNT(*) FROM base_prestige_ranks;")
rank_count = cur.fetchone()[0]
cur.execute("SELECT lang, COUNT(*) FROM base_i18n GROUP BY lang ORDER BY lang;")
lang_counts = dict(cur.fetchall())
cur.execute("""
SELECT key FROM base_i18n WHERE lang = 'DE'
EXCEPT
SELECT key FROM base_i18n WHERE lang = 'EN'
""")
only_de = [r[0] for r in cur.fetchall()]
cur.execute("""
SELECT key FROM base_i18n WHERE lang = 'EN'
EXCEPT
SELECT key FROM base_i18n WHERE lang = 'DE'
""")
only_en = [r[0] for r in cur.fetchall()]
conn.execute("VACUUM;")
conn.commit()
finally:
conn.close()
if db_path.exists():
db_path.unlink()
tmp_db_path.replace(db_path)
if export_merged is not None:
merged_chunks.append("COMMIT;\n")
export_merged.parent.mkdir(parents=True, exist_ok=True)
export_merged.write_text("\n".join(merged_chunks), encoding="utf-8", newline="\n")
print(f"[OK] Gesamtes SQL-Backup geschrieben nach: {export_merged}")
print(
f"[OK] {db_path} erfolgreich erstellt! "
f"(Dateien: {len(sql_files)} | Varianten: {variant_count} | Ränge: {rank_count} | "
f"i18n DE: {lang_counts.get('DE', 0)}, EN: {lang_counts.get('EN', 0)})"
)
if only_de or only_en:
if only_de:
print(f"[WARNUNG] Keys nur in DE vorhanden ({len(only_de)}): {', '.join(only_de)}", file=sys.stderr)
if only_en:
print(f"[WARNUNG] Keys nur in EN vorhanden ({len(only_en)}): {', '.join(only_en)}", file=sys.stderr)
return 2
return 0
except Exception as exc:
if tmp_db_path.exists():
tmp_db_path.unlink()
print(f"[FEHLER] DB-Build fehlgeschlagen: {exc}", file=sys.stderr)
return 1
def main() -> int:
root = _detect_project_root()
default_sql_dir = root / "resources" / "code_res" / "sql"
default_db_path = root / "resources" / "code_res" / "internal_base.db"
parser = argparse.ArgumentParser(description="Baut internal_base.db aus den modularen SQL-Dateien.")
parser.add_argument("--sql-dir", type=Path, default=default_sql_dir, help="Ordner mit den nummerierten .sql-Dateien")
parser.add_argument("--db-path", type=Path, default=default_db_path, help="Zielpfad für internal_base.db")
parser.add_argument("--export-merged", type=Path, default=None, help="Optional: Pfad für eine kombinierte .sql-Datei")
args = parser.parse_args()
return build_database(args.sql_dir.resolve(), args.db_path.resolve(), args.export_merged)
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -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])])
]
)

View File

@ -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

View File

@ -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)

View File

@ -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)

View File

@ -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
)
feedback_var = tk.StringVar(value=status_msg)
def get_current_acc() -> dict | None: def _format_variant_desc(self, _v_key: str, cfg: dict) -> str:
return acc_by_name.get(selected_name_var.get()) return t("bj_variant_desc", cfg["decks"], BJ_INITIAL_ANTE)
def open_bj_stats(): def _format_limit_info(self, dyn_xp_cost: int) -> str:
cur = get_current_acc() return t("bj_acc_limit_info", GOLD_MAX_ACCOUNTS, BJ_INITIAL_ANTE, dyn_xp_cost, XP_TO_GOLD_AMOUNT)
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(): def _launch_table(self, variant_key: str, acc_id: int, bots: list, resume_json: str | None = None):
cur = get_current_acc() BlackjackTableView(
if self.bot_widget is not None and has_accounts: self.ctx,
_, to_save = self.bot_widget.collect_configs() variant_key=variant_key,
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save) bj_account_id=acc_id,
self.show(preselect_id=cur["id"] if cur else None) bot_configs=bots,
on_back_to_menu=lambda aid, msg="": self.show(preselect_id=aid, status_msg=msg),
topbar_gold_txt = ( resume_state_json=resume_json,
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)

View File

@ -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']}")

View File

@ -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

View File

@ -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)
)

View File

@ -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
games/party/__init__.py Normal file
View File

View File

View File

View File

@ -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),
)

View File

@ -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

View File

@ -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)

View File

@ -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]

View File

@ -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()

View File

View File

@ -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

View File

@ -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()))

View File

@ -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")

View File

@ -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),
)

View File

View File

@ -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

View File

@ -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,
}

View File

@ -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()

View File

@ -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

View File

@ -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()))

View File

@ -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

View File

@ -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),
)

View File

@ -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.

View File

@ -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,
}

View File

@ -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")

View File

@ -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
)
feedback_var = tk.StringVar(value=status_msg)
def get_current_acc() -> dict | None: def _min_entry_for_variant(self, _v_key: str, cfg: dict) -> int:
return acc_by_name.get(selected_name_var.get()) return cfg["min_entry"]
def open_pk_stats(): def _format_variant_desc(self, _v_key: str, cfg: dict) -> str:
cur = get_current_acc() return t("pk_variant_desc", cfg["sb"], cfg["bb"], cfg["min_entry"])
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(): def _format_limit_info(self, dyn_xp_cost: int) -> str:
cur = get_current_acc() classic = PK_VARIANTS["poker_holdem"]
if self.bot_widget is not None and has_accounts: return t("pk_acc_limit_info", GOLD_MAX_ACCOUNTS, classic["sb"], classic["bb"], dyn_xp_cost, XP_TO_GOLD_AMOUNT)
_, 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 = ( def _launch_table(self, variant_key: str, acc_id: int, bots: list, resume_json: str | None = None):
t("pk_header_gold", active_acc["account_name"], active_acc["gold"]) PokerTableView(
if active_acc else "" self.ctx,
) variant_key=variant_key,
topbar = self.ctx.build_game_topbar( pk_account_id=acc_id,
self.ctx.root, bot_configs=bots,
t("pk_menu_topbar"), on_back_to_menu=lambda aid, msg="": self.show(preselect_id=aid, status_msg=msg),
on_game_menu=None, resume_state_json=resume_json,
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)

View File

@ -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()

View File

@ -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

View File

@ -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,
)

64
games/solitaire/README.md Normal file
View File

@ -0,0 +1,64 @@
# Solitaire-Framework (`games/solitaire`)
Dieses Verzeichnis bildet das gemeinsame technische Fundament aller Solo-Kartenspiele der **Goth Cardgame Collection** (Kategorie `CAT_SOLO`). Alle enthaltenen Solitaire-Spiele teilen sich eine einheitliche Engine-Basis, flüssige Canvas-Animationen, das gerahmte Tisch-Rendering sowie das persistente Speicher- und Statistiksystem.
---
## Enthaltene Module
| Unterordner | Spiel | Varianten (`variant_key`) | Besonderheiten |
| :--- | :--- | :--- | :--- |
| `base/` | Gemeinsamer Unterbau | — | Basis-Engine, 60-FPS-Animator, Tisch-Theme & In-Game-Statistik |
| `klondike/` | **Klondike** | `klondike_1`, `klondike_3` | 7 Spalten, 1er-/3er-Ziehen, 3-Zyklen-Stagnationssperre |
| `freecell/` | **FreeCell** | `freecell_std` | 8 Spalten (alle offen), 4 Freie Zellen, Supermove-Formel |
| `spider_solitaire/` | **Spider Solitaire** | `spider_1suit`, `spider_2suit`, `spider_4suit` | 10 Spalten, 104 Karten, strenge Austeil-Regel, 8 Farb-Sequenzen |
---
## Architektur von `games/solitaire/base/`
* **`solitaire_core.py`**
* Definiert `SolitaireCard` (inklusive `deck_id` zur eindeutigen Identifikation bei Doppeldecks wie in Spider Solitaire), Deck-Generatoren sowie Sequenzprüfer (`is_alternating_descending`, `is_same_suit_descending`).
* Stellt `SolitaireBaseEngine` bereit: verwaltet Punkte, Zugzähler, unbegrenztes **Undo** bis zurück zu Zug $0$, **Undo All** (`_initial_board_json`), JSON-Serialisierung und die Spielzeitmessung.
* **`card_animator.py`**
* Enthält den nicht-blockierenden `CardFlightAnimator` (~70 FPS Zielrate mit kubischem Ease-Out $1 - (1 - t)^3$).
* Nutzt leichtgewichtiges Canvas-Tag-Moving (`canvas.move`) und beendet laufende Flüge bei schnellen Folgeklicks verzögerungsfrei per `flush()`, sodass keinerlei Input-Lag entsteht.
* **`solitaire_theme.py`**
* `SolitaireTableBgRenderer`: Skaliert `resources/images/general_table.jpg` gecacht auf die aktuelle Canvas-Größe und berechnet über `get_frame_insets()` dynamisch die Rahmen-Abstände, damit keine Karte in den verzierten Holz- und Kerzenrahmen ragt.
* `get_game_icon_photo()`: Extrahiert das höchstaufgelöste Bild aus den `.ico`-Dateien unter `resources/images/game_icons/`, schneidet Ränder automatisch frei und maskiert abgerundete Ecken per $2\times$-Supersampling.
* **`solitaire_stats_view.py`**
* Einheitliche In-Game-Statistikansicht mit Direkt-Umschaltern für alle Varianten eines Spiels sowie Gesamtübersicht.
---
## Übergreifende Solo-Mechaniken
### 1. Garantiert lösbare Deals & 4 Schwierigkeitsgrade
Zufällige unlösbare Kartenverteilungen werden vor Spielbeginn durch spielspezifische Solver bzw. konstruktive Generatoren ausgefiltert. Jede Partie lässt sich in vier Stufen starten:
| Stufe | Rang-Bezeichnung | Charakteristik | Schwierigkeits-Multiplikator |
| :---: | :--- | :--- | :---: |
| `0` | **Stufe 1 – Akolyth (Leicht)** | Offene Struktur, frühe Anschlüsse | $\times 0.85$ |
| `1` | **Stufe 2 – Nachtwanderer (Normal)** | Klassisch ausgewogenes Spielgefühl | $\times 1.00$ |
| `2` | **Stufe 3 – Großmeister (Schwer)** | Tiefe Blockaden & engere Pfade | $\times 1.25$ |
| `3` | **Stufe 4 – Gottheit (Gnadenlos)** | Vergrabene Schlüsselkarten & minimales Fehlertoleranzfenster | $\times 1.55$ |
### 2. Verzögerter Timer & Fokus-Pause
* Nach dem Austeilen bleibt die Uhr bei `00:00` stehen, damit das Spielfeld in Ruhe analysiert werden kann.
* Erst die **erste echte Interaktion** (Klick auf eine Karte, den Nachziehstapel oder den Tipp-Button) startet den Timer.
* Verliert das Spielfenster den Fokus oder wird es minimiert, pausiert die Zeitmessung automatisch und sichert den aktuellen Stand.
### 3. Persistenz, Sackgassen-Erkennung & XP-Regeln
* **Auto-Save & Resume:** Jeder Zug sowie das Schließen des Fensters (`<Destroy>`) speichert den kompletten Spielzustand inklusive kompletter Undo-Historie in `user_data.db`.
* **Sackgassen-Dialog:** Erkennt die Engine, dass kein sinnvoller Zug mehr existiert, öffnet sich automatisch ein Dialog mit den Optionen *Schritt zurück*, *Alles auf Anfang* oder *Partie aufgeben*.
* **Aufgabe-Abzug:** Da jedes Deck lösbar ist, wird das Abbrechen einer bereits begonnenen Runde (`moves > 0`) als Niederlage gewertet und zieht $40\,\%$ der regulären Sieg-XP ab (geschützt durch das *Schöpfergeist V*-Minimum nach Erreichen des Gottheit-Rangs).
---
## Einheitliche Tastatur- & Maussteuerung
* **Linksklick + Ziehen:** Einzelkarte oder gültige Kartenkette per Drag & Drop verschieben (ungültige Züge gleiten per Snap-Back zurück).
* **Doppelklick oder Rechtsklick:** Intelligenter *Smart-Auto-Move* auf die beste verfügbare Zielposition.
* **`Strg + Z`:** Einen Zug rückgängig machen (lückenlos bis zurück zu Zug $0$).
* **`Strg + Umschalt + Z`:** Komplette Auslage auf den Startzustand zurücksetzen (*⟲ Anfang*, Spielzeit läuft weiter).
* **`H`:** Kontextsensitiven Zug-Tipp auf dem Spielfeld hervorheben.

View File

Binary file not shown.

View File

@ -0,0 +1,352 @@
# -*- coding: utf-8 -*-
# games/solitaire/base/card_animator.py
from __future__ import annotations
import random
import time
import tkinter as tk
from typing import Callable, Iterable
from PIL import Image, ImageTk
class CardFlightAnimator:
"""
Zentraler, nicht-blockierender Canvas-Animator für alle Solitaire-Tische:
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
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):
self.root = root
self.canvas = canvas
# 1. Lineare Kartenflüge
self._job: str | None = None
self._flights: list[dict] = []
self._on_done: Callable[[], None] | None = None
self._start_ts: float = 0.0
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
def is_active(self) -> bool:
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):
"""Bricht alle laufenden Flug-, Fall- und Wackel-Timer sofort sauber ab."""
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
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):
"""Beendet eine laufende Flug-Animation sofort sauber im Zielzustand."""
if not self.is_active:
return
cb = self._on_done
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):
cb()
# ------------------------------------------------------------------
# 1. Lineare Kartenflüge (Tableau / Foundation / Talon -> Waste)
# ------------------------------------------------------------------
def start(
self,
flights: list[dict],
draw_card_cb: Callable,
duration_ms: int = 115,
on_done: Callable[[], None] | None = None,
):
self.flush()
if not flights or not self._canvas_alive():
if callable(on_done):
on_done()
return
active_flights: list[dict] = []
max_dist = 0.0
for idx, item in enumerate(flights):
sx, sy = item["start"]
ex, ey = item["end"]
dist = ((ex - sx) ** 2 + (ey - sy) ** 2) ** 0.5
if dist > max_dist:
max_dist = dist
tag = f"anim_item_{idx}"
draw_card_cb(
item["card"],
int(round(sx)),
int(round(sy)),
tags=("anim_flight", tag),
highlight_color=item.get("highlight"),
)
active_flights.append({
"tag": tag,
"sx": float(sx),
"sy": float(sy),
"ex": float(ex),
"ey": float(ey),
"cur_x": float(sx),
"cur_y": float(sy),
})
if max_dist < 4.0:
self.canvas.delete("anim_flight")
if callable(on_done):
on_done()
return
scaled_ms = max(
65, min(165, int(duration_ms * (0.72 + min(1.0, max_dist / 520.0) * 0.45)))
)
self._flights = active_flights
self._on_done = on_done
self._duration_sec = scaled_ms / 1000.0
self._start_ts = time.perf_counter()
self._step()
def _step(self):
self._job = None
if not self._canvas_alive():
self._flights.clear()
self._on_done = None
return
elapsed = time.perf_counter() - self._start_ts
t_raw = min(1.0, max(0.0, elapsed / max(0.001, self._duration_sec)))
ease = 1.0 - ((1.0 - t_raw) ** 3)
for fl in self._flights:
nx = fl["sx"] + (fl["ex"] - fl["sx"]) * ease
ny = fl["sy"] + (fl["ey"] - fl["sy"]) * ease
dx = nx - fl["cur_x"]
dy = ny - fl["cur_y"]
if abs(dx) >= 0.25 or abs(dy) >= 0.25:
self.canvas.move(fl["tag"], dx, dy)
fl["cur_x"] = nx
fl["cur_y"] = ny
if t_raw >= 1.0:
cb = self._on_done
self._flights.clear()
self._on_done = None
try:
self.canvas.delete("anim_flight")
except Exception:
pass
if callable(cb):
cb()
return
try:
self._job = self.root.after(self.FRAME_MS, self._step)
except Exception:
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)

View File

@ -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

View File

@ -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()

View File

@ -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)

View File

@ -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)),
)

View File

@ -0,0 +1,256 @@
# -*- coding: utf-8 -*-
# games/solitaire/base/solitaire_core.py
from __future__ import annotations
import json
import random
import time
from games.solitaire.base.solitaire_card import (
RANK_VALUES,
SOLITAIRE_RANKS,
SolitaireCard,
)
from resources.code_res.game_constants import SUITS
__all__ = [
"SOLITAIRE_RANKS",
"RANK_VALUES",
"SolitaireCard",
"SolitaireBaseEngine",
"create_solitaire_deck",
"is_alternating_descending",
"is_same_suit_descending",
]
def create_solitaire_deck(
num_decks: int = 1,
suits: tuple[str, ...] = SUITS,
shuffle: bool = True,
rng: random.Random | None = None,
) -> list[SolitaireCard]:
if not suits:
raise ValueError("suits darf nicht leer sein.")
total_suit_sets = 4 * num_decks
cards: list[SolitaireCard] = []
for set_idx in range(total_suit_sets):
suit = suits[set_idx % len(suits)]
for rank in SOLITAIRE_RANKS:
cards.append(SolitaireCard(suit=suit, rank=rank, face_up=False, deck_id=set_idx))
if shuffle:
(rng or random).shuffle(cards)
return cards
def is_alternating_descending(cards: list[SolitaireCard]) -> bool:
if not cards or any(not c.face_up for c in cards):
return False
for idx in range(len(cards) - 1):
upper, lower = cards[idx], cards[idx + 1]
if upper.is_red == lower.is_red or upper.value != lower.value + 1:
return False
return True
def is_same_suit_descending(cards: list[SolitaireCard]) -> bool:
if not cards or any(not c.face_up for c in cards):
return False
for idx in range(len(cards) - 1):
upper, lower = cards[idx], cards[idx + 1]
if upper.suit != lower.suit or upper.value != lower.value + 1:
return False
return True
class SolitaireBaseEngine:
"""
Gemeinsame Basis für Zugzähler, Punkte, verzögerten Timer-Start (erst ab 1. Klick),
Fokus-Pause und unbegrenztes Undo bis zum Spielstart.
"""
def __init__(self):
self.moves: int = 0
self.score: int = 0
self.won: bool = False
self._timer_started: bool = False
self._elapsed_offset_sec: float = 0.0
self._session_start_ts: float | None = None
self._finished_duration_sec: float | None = None
self._undo_stack: list[str] = []
self._initial_board_json: str | None = None
def reset_tracking(self):
self.moves = 0
self.score = 0
self.won = False
self._timer_started = False
self._elapsed_offset_sec = 0.0
self._session_start_ts = None
self._finished_duration_sec = None
self._undo_stack.clear()
self._initial_board_json = None
def capture_initial_state(self):
"""Merkt sich die exakte Startverteilung nach dem Austeilen für lückenloses Zurückgehen & Undo-All."""
self._initial_board_json = json.dumps(self.serialize_board(), separators=(",", ":"))
@property
def has_timer_started(self) -> bool:
return self._timer_started
@property
def is_timer_paused(self) -> bool:
# Solange die Partie noch gar nicht begonnen wurde (Umschau-Phase), gilt sie nicht als pausiert
return self._timer_started and self._session_start_ts is None and self._finished_duration_sec is None
def start_timer_if_needed(self):
"""Startet die Spielzeit genau bei der ersten echten Spieler-Interaktion."""
if self.won or self._finished_duration_sec is not None:
return
if not self._timer_started:
self._timer_started = True
self._session_start_ts = time.monotonic()
elif self._session_start_ts is None:
self._session_start_ts = time.monotonic()
def pause_timer(self):
if not self._timer_started or self._finished_duration_sec is not None or self._session_start_ts is None:
return
self._elapsed_offset_sec += max(0.0, time.monotonic() - self._session_start_ts)
self._session_start_ts = None
def resume_timer(self):
"""Setzt die Uhr nach Fokus-Rückkehr nur fort, wenn das Spiel bereits aktiv gestartet war."""
if not self._timer_started or self._finished_duration_sec is not None or self.won:
return
if self._session_start_ts is None:
self._session_start_ts = time.monotonic()
def get_elapsed_seconds(self) -> float:
if self._finished_duration_sec is not None:
return self._finished_duration_sec
if not self._timer_started:
return 0.0
if self._session_start_ts is None:
return self._elapsed_offset_sec
return self._elapsed_offset_sec + max(0.0, time.monotonic() - self._session_start_ts)
def mark_won(self):
if not self.won:
self._finished_duration_sec = self.get_elapsed_seconds()
self._session_start_ts = None
self.won = True
@property
def can_undo(self) -> bool:
if self.won:
return False
if self._undo_stack:
return True
if self._initial_board_json and self.moves > 0:
cur_json = json.dumps(self.serialize_board(), separators=(",", ":"))
return cur_json != self._initial_board_json
return False
@property
def can_undo_all(self) -> bool:
return self.can_undo
def push_undo(self):
"""Speichert jeden einzelnen Schritt lückenlos und stellt sicher, dass der Timer läuft."""
self.start_timer_if_needed()
snap = json.dumps(self._snapshot_dict(), separators=(",", ":"))
self._undo_stack.append(snap)
def undo(self) -> bool:
if self.won:
return False
if self._undo_stack:
raw = self._undo_stack.pop()
data = json.loads(raw)
self._restore_snapshot_dict(data)
return True
if self.can_undo and self._initial_board_json:
return self.undo_all()
return False
def undo_all(self) -> bool:
"""Setzt das komplette Brett sofort auf Zug 0 zurück; einmal gestartete Spielzeit läuft weiter."""
if not self.can_undo_all or not self._initial_board_json:
return False
board_data = json.loads(self._initial_board_json)
self.restore_board(board_data)
self._undo_stack.clear()
self.moves = 0
self.score = 0
return True
def _snapshot_dict(self) -> dict:
return {
"moves": self.moves,
"score": self.score,
"board": self.serialize_board(),
}
def _restore_snapshot_dict(self, data: dict):
self.moves = int(data.get("moves", 0))
self.score = int(data.get("score", self.score))
self.restore_board(data["board"])
def to_json(self) -> str:
payload = {
"moves": self.moves,
"score": self.score,
"won": self.won,
"timer_started": self._timer_started,
"elapsed_sec": round(self.get_elapsed_seconds(), 2),
"board": self.serialize_board(),
"initial_board": json.loads(self._initial_board_json) if self._initial_board_json else None,
"undo": self._undo_stack,
}
return json.dumps(payload, separators=(",", ":"))
def load_json(self, raw_json: str):
data = json.loads(raw_json)
self.moves = int(data.get("moves", 0))
self.score = int(data.get("score", 0))
self.won = bool(data.get("won", False))
self._elapsed_offset_sec = float(data.get("elapsed_sec", 0.0))
# Abwärtskompatibel: War das Spiel schon in Bewegung, läuft der Timer weiter;
# war es ein frisch gegebenes Deck bei 0 Zügen & 0s, bleibt die Uhr bis zum 1. Klick stehen.
raw_started = data.get("timer_started")
if raw_started is None:
self._timer_started = (self.moves > 0) or (self._elapsed_offset_sec > 0.0)
else:
self._timer_started = bool(raw_started)
if self.won:
self._session_start_ts = None
self._finished_duration_sec = self._elapsed_offset_sec
elif self._timer_started:
self._session_start_ts = time.monotonic()
self._finished_duration_sec = None
else:
self._session_start_ts = None
self._finished_duration_sec = None
self._undo_stack = list(data.get("undo", []))
self.restore_board(data["board"])
init_b = data.get("initial_board")
if init_b is not None:
self._initial_board_json = json.dumps(init_b, separators=(",", ":"))
elif self._undo_stack:
first_snap = json.loads(self._undo_stack[0])
self._initial_board_json = json.dumps(first_snap["board"], separators=(",", ":"))
else:
self.capture_initial_state()
def serialize_board(self) -> dict:
raise NotImplementedError
def restore_board(self, board: dict):
raise NotImplementedError

View File

@ -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)

View File

@ -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

View File

@ -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()

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -0,0 +1,169 @@
# -*- coding: utf-8 -*-
# games/solitaire/base/solitaire_theme.py
from __future__ import annotations
from pathlib import Path
import tkinter as tk
import warnings
from PIL import Image, ImageChops, ImageDraw, ImageTk
_ICON_PIL_CACHE: dict[Path, Image.Image] = {}
_ICON_TK_CACHE: dict[tuple[Path, int], ImageTk.PhotoImage] = {}
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:
with warnings.catch_warnings():
warnings.simplefilter("ignore", UserWarning)
with Image.open(icon_path) as ico:
ico_helper = getattr(ico, "ico", None)
best_img = None
if ico_helper is not None and hasattr(ico_helper, "sizes"):
best_img = _pick_largest_rgba_frame(ico_helper.sizes(), ico_helper.getimage)
if best_img is None:
best_img = _pick_largest_rgba_frame(
range(getattr(ico, "n_frames", 1)),
lambda idx: (ico.seek(idx), ico.copy())[1],
)
return best_img if best_img is not None else ico.convert("RGBA")
except Exception:
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:
w, h = img.size
px = img.load()
def is_badge_pixel(r: int, g: int, b: int, a: int) -> bool:
return a >= 40 and not (r > 228 and g > 228 and b > 228)
valid_rows = _scan_badge_axis(h, w, lambda y, x: is_badge_pixel(*px[x, y]))
valid_cols = _scan_badge_axis(w, h, lambda x, y: is_badge_pixel(*px[x, y]))
cropped = (
img.crop((valid_cols[0], valid_rows[0], valid_cols[-1] + 1, valid_rows[-1] + 1))
if (valid_rows and valid_cols)
else img
)
side = max(cropped.width, cropped.height)
square = cropped.resize((side, side), Image.Resampling.LANCZOS)
mask_big = Image.new("L", (side * 2, side * 2), 0)
draw = ImageDraw.Draw(mask_big)
pad = int(side * 2 * 0.008)
draw.rounded_rectangle(
(pad, pad, side * 2 - 1 - pad, side * 2 - 1 - pad),
radius=int(side * 2 * 0.195),
fill=255,
)
mask = mask_big.resize((side, side), Image.Resampling.LANCZOS)
square.putalpha(ImageChops.multiply(square.getchannel("A"), mask))
return square
def get_game_icon_photo(res_mgr, game_folder: str, size_px: int = 92) -> ImageTk.PhotoImage | None:
icon_path = res_mgr.get_game_icon_path(game_folder)
if icon_path is None:
return None
cache_key = (icon_path, size_px)
if cache_key in _ICON_TK_CACHE:
return _ICON_TK_CACHE[cache_key]
if icon_path not in _ICON_PIL_CACHE:
raw = extract_best_ico_pil(icon_path)
if raw is None:
return None
_ICON_PIL_CACHE[icon_path] = _auto_crop_and_round_badge(raw)
photo = ImageTk.PhotoImage(_ICON_PIL_CACHE[icon_path].resize((size_px, size_px), Image.Resampling.LANCZOS))
_ICON_TK_CACHE[cache_key] = photo
return photo
class SolitaireTableBgRenderer:
"""Zeichnet den nahtlosen Fenster-Hintergrundausschnitt auf das Tisch-Canvas."""
FRAME_X_RATIO = 0.075
FRAME_TOP_RATIO = 0.095
FRAME_BOT_RATIO = 0.090
def __init__(self, res_mgr):
self.res_mgr = res_mgr
self._raw_pil: Image.Image | None = None
self._loaded = False
self._slice_photo: ImageTk.PhotoImage | None = None
def _ensure_pil(self) -> Image.Image | None:
if not self._loaded:
self._loaded = True
bg_path = self.res_mgr.get_ui_image_path("general_table")
if bg_path.is_file():
try:
with Image.open(bg_path) as im:
self._raw_pil = im.convert("RGB")
except Exception:
self._raw_pil = None
return self._raw_pil
def get_frame_insets(self, canvas_w: int, canvas_h: int) -> tuple[int, int, int]:
if self._ensure_pil() is None:
return max(20, int(canvas_w * 0.04)), max(14, int(canvas_h * 0.022)), 16
return (
max(36, int(canvas_w * self.FRAME_X_RATIO)),
max(28, int(canvas_h * self.FRAME_TOP_RATIO)),
max(26, int(canvas_h * self.FRAME_BOT_RATIO)),
)
def draw_on_canvas(self, canvas: tk.Canvas, canvas_w: int, canvas_h: int):
if canvas_w < 80 or canvas_h < 80:
return
root = canvas.winfo_toplevel()
assets = getattr(root, "assets", None)
if assets is None:
return
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")

View File

@ -0,0 +1,64 @@
# FreeCell (`games/solitaire/freecell`)
Strategisches Solitaire mit vollständiger Information: Alle $52$ Karten liegen von Beginn an offen auf acht Spalten. Zufallsglück beim Aufdecken entfällt komplett – über Sieg oder Sackgasse entscheidet allein das Haushalten mit den vier freien Zellen und leeren Hilfsspalten.
---
## Spielvariante
| Variante (`variant_key`) | Layout | Kartenrücken | Basis-XP |
| :--- | :--- | :---: | :---: |
| `freecell_std` | $8$ Spalten ($4\times 7$, $4\times 6$), $4$ Freie Zellen, $4$ Foundations | Schwarz (`Back_Black.png`) | $\times 1.15$ |
---
## Spielregeln & Supermove-Formel
1. **Freie Zellen (oben links):** Vier Zwischenspeicher, die jeweils **genau eine einzelne Karte** aufnehmen können.
2. **Foundations (oben rechts):** Vier Zielstapel (`♣`, `♦`, `♥`, `♠`), die aufsteigend von **Ass (`A`) bis König (`K`)** aufgebaut werden.
3. **Tableau (8 Spalten):** Gebaut wird absteigend mit wechselnden Farben. In eine leere Spalte darf jede beliebige Einzelkarte (oder ein zulässiger geordneter Stapel) gelegt werden.
4. **Supermove-Kapazität:** Obwohl streng genommen immer nur eine Karte gleichzeitig gezogen wird, erlaubt die Engine das komfortable Bewegen ganzer wechselnd-absteigender Kartenketten der Länge $L$ in einem Zug, sofern genügend freie Pufferplätze existieren:
$$L \le (F + 1) \cdot 2^{E_{\text{aux}}}$$
Dabei gilt:
* $F$: Anzahl der aktuell leeren Freien Zellen ($0 \le F \le 4$)
* $E_{\text{aux}}$: Anzahl der aktuell leeren Tableau-Spalten, die als **Zwischenpuffer** dienen. Wird direkt **in** eine leere Zielspalte gezogen, zählt diese Zielspalte selbst nicht als Hilfspuffer mit ($E_{\text{aux}} = \max(0, E_{\text{gesamt}} - 1)$).
* Die aktuelle Maximalkapazität wird live oben in der HUD-Leiste angezeigt; bei Überschreitung gibt die Statuszeile direkt aus, wie viele Karten maximal auf einmal bewegt werden dürfen.
---
## Solver & Smart-Controls (`freecell_solver.py`)
* **Best-First-Solver:** Nutzt kanonische Zustandssymmetrie (sortierte FreeCells und Spalten) sowie sichere Auto-Foundation-Promotion, um unlösbare Verteilungen (wie das bekannte Deal #11982) zuverlässig vor Spielstart auszusortieren und die strukturelle Schwierigkeit (`0` *Leicht* bis `3` *Gottheit*) präzise einzustufen.
* **Smart-Auto-Move (Doppelklick / Rechtsklick):** Prüft in absteigender Priorität:
1. Direkte Ablage auf die passende Foundation
2. Anlegen an eine passende belegte Tableau-Spalte (inklusive Supermove)
3. Auslagern auf eine leere Tableau-Spalte
4. Parken einer einzelnen Spaltenspitze in der ersten freien Zelle
* **Auto-Ende (`⚡ Auto-Ende`):** Aktiviert sich automatisch, sobald jede der acht Spalten für sich monoton absteigend geordnet ist (keine kleinere Karte mehr unter einer höheren Karte blockiert).
---
## Erfahrungspunkte & Speed-Bonus
$$\text{Mult}_{\text{gesamt}} = 1.15 \cdot \text{Mult}_{\text{Stufe}} \cdot \text{Bonus}_{\text{Zeit}}(t)$$
* **Voller Speed-Bonus ($\times 1.25$):** Sieg in $t \le 180\,\text{s}$ ($3{:}00$ Min.)
* **Kleiner Speed-Bonus ($\times 1.12$):** Sieg in $180\,\text{s} < t \le 330\,\text{s}$ ($5{:}30$ Min.)
* **Standard ($\times 1.00$):** Sieg in $t > 330\,\text{s}$
---
## Dateistruktur
```text
games/solitaire/freecell/
├── start.py # Einstiegspunkt & Kategorie-Registrierung (CAT_SOLO)
├── models/
│ ├── freecell_solver.py # Best-First-Solver, Symmetriebrechung & Härte-Bewertung
│ └── freecell_engine.py # Supermove-Logik, FreeCell-Regeln, Hints & Deadlock-Check
└── views/
├── freecell_menu_view.py # Schwierigkeitsauswahl, Statistik-Zugang & Resume-Modal
└── freecell_table_view.py # Symmetrisches 8-Spalten-Canvas mit Live-Kapazitätsanzeige
```

View File

View File

@ -0,0 +1,461 @@
# -*- coding: utf-8 -*-
# games/solitaire/freecell/models/freecell_engine.py
from __future__ import annotations
from games.solitaire.base.solitaire_core import (
SolitaireBaseEngine,
SolitaireCard,
is_alternating_descending,
)
from games.solitaire.freecell.models.freecell_solver import generate_solvable_freecell_columns
from resources.code_res.game_constants import SUITS
class FreeCellEngine(SolitaireBaseEngine):
"""
Vollständige FreeCell-Spiellogik:
- 8 Tableau-Spalten (4x 7 Karten, 4x 6 Karten, alle offen)
- 4 Freie Zellen (je max. 1 Karte)
- 4 Foundations (fest nach SUITS geordnet)
- Supermove-Formel: max_cards = (empty_freecells + 1) * (2 ** empty_aux_columns)
"""
NUM_TABLEAU = 8
NUM_FREECELLS = 4
NUM_FOUNDATIONS = 4
SCORE_TO_FOUNDATION = 10
SCORE_FOUNDATION_BACK = -15
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.freecells: list[SolitaireCard | None] = [None] * self.NUM_FREECELLS
self.foundations: list[list[SolitaireCard]] = [[] for _ in range(self.NUM_FOUNDATIONS)]
self.tableau: list[list[SolitaireCard]] = [[] for _ in range(self.NUM_TABLEAU)]
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.reset_tracking()
self.freecells = [None] * self.NUM_FREECELLS
self.foundations = [[] for _ in range(self.NUM_FOUNDATIONS)]
self.tableau = generate_solvable_freecell_columns(difficulty=self.difficulty, seed=seed)
self.capture_initial_state()
def _add_score(self, delta: int):
self.score = max(0, self.score + delta)
def _check_victory(self) -> bool:
if sum(len(f) for f in self.foundations) == 52:
self.mark_won()
return True
return False
# --- Kapazität & Regel-Prüfungen ---
def foundation_index_for_suit(self, suit: str) -> int:
return SUITS.index(suit)
@property
def empty_freecell_count(self) -> int:
return sum(1 for c in self.freecells if c is None)
@property
def empty_tableau_count(self) -> int:
return sum(1 for col in self.tableau if not col)
def max_movable_cards(self, target_is_empty_tableau: bool = False) -> int:
"""
Klassische FreeCell-Supermove-Kapazität:
(freie Zellen + 1) * 2^(freie Hilfsspalten).
Ist die Zielspalte selbst leer, steht sie nicht als Zwischenpuffer zur Verfügung.
"""
aux_empty = self.empty_tableau_count - (1 if target_is_empty_tableau else 0)
aux_empty = max(0, aux_empty)
return (self.empty_freecell_count + 1) * (1 << aux_empty)
def can_grab_tableau_stack(self, col_idx: int, start_idx: int) -> bool:
"""Prüft, ob ab start_idx bis unten eine gültige wechselnd-absteigende Kette vorliegt."""
if not (0 <= col_idx < self.NUM_TABLEAU):
return False
col = self.tableau[col_idx]
if not (0 <= start_idx < len(col)):
return False
return is_alternating_descending(col[start_idx:])
def can_move_to_freecell(self, cell_idx: int) -> bool:
return 0 <= cell_idx < self.NUM_FREECELLS and self.freecells[cell_idx] is None
def first_empty_freecell(self) -> int | None:
for idx, c in enumerate(self.freecells):
if c is None:
return idx
return None
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):
return False
if card.suit != SUITS[found_idx]:
return False
pile = self.foundations[found_idx]
if not pile:
return card.value == 1
return card.value == pile[-1].value + 1
def check_tableau_drop(self, moving_cards: list[SolitaireCard], dst_col: int) -> tuple[bool, str]:
"""
Gibt (erlaubt, grund) zurück.
grund == 'capacity' signalisiert dem UI, dass die Reihenfolge stimmt,
aber aktuell zu wenige freie Zellen/Spalten für den Supermove offen sind.
"""
if not moving_cards or not (0 <= dst_col < self.NUM_TABLEAU):
return False, "invalid"
if not is_alternating_descending(moving_cards):
return False, "sequence"
dst = self.tableau[dst_col]
is_empty_dst = len(dst) == 0
if not is_empty_dst:
top = dst[-1]
head = moving_cards[0]
if top.is_red == head.is_red or top.value != head.value + 1:
return False, "mismatch"
cap = self.max_movable_cards(target_is_empty_tableau=is_empty_dst)
if len(moving_cards) > cap:
return False, "capacity"
return True, "ok"
def can_move_to_tableau(self, moving_cards: list[SolitaireCard], dst_col: int) -> bool:
ok, _reason = self.check_tableau_drop(moving_cards, dst_col)
return ok
# --- Aktionen: Kartenverschiebungen ---
def move_tableau_to_freecell(self, src_col: int, cell_idx: int | None = None) -> bool:
if self.won or not (0 <= src_col < self.NUM_TABLEAU) or not self.tableau[src_col]:
return False
target_cell = self.first_empty_freecell() if cell_idx is None else cell_idx
if target_cell is None or not self.can_move_to_freecell(target_cell):
return False
self.push_undo()
self.freecells[target_cell] = self.tableau[src_col].pop()
self.moves += 1
return True
def move_freecell_to_freecell(self, src_cell: int, dst_cell: int) -> bool:
if self.won or src_cell == dst_cell:
return False
if not (0 <= src_cell < self.NUM_FREECELLS and self.can_move_to_freecell(dst_cell)):
return False
if self.freecells[src_cell] is None:
return False
self.push_undo()
self.freecells[dst_cell] = self.freecells[src_cell]
self.freecells[src_cell] = None
self.moves += 1
return True
def move_freecell_to_foundation(self, src_cell: int, found_idx: int | None = None) -> bool:
if self.won or not (0 <= src_cell < self.NUM_FREECELLS):
return False
card = self.freecells[src_cell]
if card is None:
return False
target_f = self.foundation_index_for_suit(card.suit) if found_idx is None else found_idx
if not self.can_move_to_foundation(card, target_f):
return False
self.push_undo()
self.freecells[src_cell] = None
self.foundations[target_f].append(card)
self.moves += 1
self._add_score(self.SCORE_TO_FOUNDATION)
self._check_victory()
return True
def move_tableau_to_foundation(self, src_col: int, found_idx: int | None = None) -> bool:
if self.won or not (0 <= src_col < self.NUM_TABLEAU) or not self.tableau[src_col]:
return False
card = self.tableau[src_col][-1]
target_f = self.foundation_index_for_suit(card.suit) if found_idx is None else found_idx
if not self.can_move_to_foundation(card, target_f):
return False
self.push_undo()
self.tableau[src_col].pop()
self.foundations[target_f].append(card)
self.moves += 1
self._add_score(self.SCORE_TO_FOUNDATION)
self._check_victory()
return True
def move_freecell_to_tableau(self, src_cell: int, dst_col: int) -> bool:
if self.won or not (0 <= src_cell < self.NUM_FREECELLS):
return False
card = self.freecells[src_cell]
if card is None or not self.can_move_to_tableau([card], dst_col):
return False
self.push_undo()
self.freecells[src_cell] = None
self.tableau[dst_col].append(card)
self.moves += 1
return True
def move_tableau_to_tableau(self, src_col: int, start_idx: int, dst_col: int) -> bool:
if self.won or src_col == dst_col:
return False
if not (0 <= src_col < self.NUM_TABLEAU and 0 <= dst_col < self.NUM_TABLEAU):
return False
col = self.tableau[src_col]
if not (0 <= start_idx < len(col)):
return False
moving = col[start_idx:]
if not self.can_move_to_tableau(moving, dst_col):
return False
self.push_undo()
del col[start_idx:]
self.tableau[dst_col].extend(moving)
self.moves += 1
return True
def move_foundation_to_tableau(self, found_idx: int, dst_col: int) -> bool:
if self.won or not (0 <= found_idx < self.NUM_FOUNDATIONS):
return False
pile = self.foundations[found_idx]
if not pile or not self.can_move_to_tableau([pile[-1]], dst_col):
return False
self.push_undo()
card = pile.pop()
self.tableau[dst_col].append(card)
self.moves += 1
self._add_score(self.SCORE_FOUNDATION_BACK)
return True
def move_foundation_to_freecell(self, found_idx: int, cell_idx: int) -> bool:
if self.won or not (0 <= found_idx < self.NUM_FOUNDATIONS):
return False
pile = self.foundations[found_idx]
if not pile or not self.can_move_to_freecell(cell_idx):
return False
self.push_undo()
self.freecells[cell_idx] = pile.pop()
self.moves += 1
self._add_score(self.SCORE_FOUNDATION_BACK)
return True
# --- Komfort: Auto-Complete, Hinweise & Sackgassen-Prüfung ---
def can_auto_complete(self) -> bool:
"""
Aktiv, sobald jede Tableau-Spalte für sich monoton fallend sortiert ist
(keine kleinere Karte mehr unter einer größeren Karte eingeklemmt).
"""
if self.won:
return False
for col in self.tableau:
for i in range(len(col) - 1):
if col[i].value < col[i + 1].value:
return False
return True
def auto_complete_step(self, record_undo: bool = False) -> bool:
if self.won:
return False
candidates: list[tuple[int, str, int, int]] = []
for fc_i, c in enumerate(self.freecells):
if c is not None:
f_idx = self.foundation_index_for_suit(c.suit)
if self.can_move_to_foundation(c, f_idx):
candidates.append((c.value, "freecell", fc_i, f_idx))
for col_i, col in enumerate(self.tableau):
if col:
c = col[-1]
f_idx = self.foundation_index_for_suit(c.suit)
if self.can_move_to_foundation(c, f_idx):
candidates.append((c.value, "tableau", col_i, f_idx))
if not candidates:
return False
candidates.sort(key=lambda item: item[0])
_val, zone, src_idx, f_idx = candidates[0]
if record_undo:
self.push_undo()
if zone == "freecell":
card = self.freecells[src_idx]
self.freecells[src_idx] = None
else:
card = self.tableau[src_idx].pop()
assert card is not None
self.foundations[f_idx].append(card)
self.moves += 1
self._add_score(self.SCORE_TO_FOUNDATION)
self._check_victory()
return True
def has_any_meaningful_move(self) -> bool:
"""
Erkennt echte FreeCell-Deadlocks (alle 4 FreeCells voll, keine leere Spalte,
keine Karte passt auf Foundation oder eine andere Tableau-Spitze).
"""
if self.won:
return True
# Sobald mindestens eine FreeCell frei ist oder eine Spalte leer ist, kann noch rangiert werden
if self.empty_freecell_count > 0 or self.empty_tableau_count > 0:
return True
# 1. Irgendeine FreeCell- oder Tableau-Karte auf Foundation?
for c in self.freecells:
if c is not None and self.can_move_to_foundation(c, self.foundation_index_for_suit(c.suit)):
return True
for col in self.tableau:
if col and self.can_move_to_foundation(col[-1], self.foundation_index_for_suit(col[-1].suit)):
return True
# 2. FreeCell -> belegte Tableau-Spalte?
for fc_i, c in enumerate(self.freecells):
if c is not None:
for dst_col in range(self.NUM_TABLEAU):
if self.can_move_to_tableau([c], dst_col):
return True
# 3. Tableau -> belegte Tableau-Spalte? (bei 0 freien Zellen/Spalten ist Kapazität = 1, also nur Einzelspitze)
for src_col, col in enumerate(self.tableau):
if not col:
continue
top = col[-1]
# Verhindere reines Hin-und-Her derselben Karte zwischen zwei gleichwertigen Elternkarten,
# außer darunter liegt eine andere Karte, die dadurch spielbar wird.
for dst_col in range(self.NUM_TABLEAU):
if src_col != dst_col and self.can_move_to_tableau([top], dst_col):
if len(col) >= 2:
prev_parent = col[-2]
new_parent = self.tableau[dst_col][-1]
# Wenn Karte schon auf gültigem Gegenfarben-Elternteil liegt (z.B. schwarze 7 auf roter 8)
# und nur auf die andere rote 8 wechselt, prüfen ob prev_parent danach selbst wohin kann
if prev_parent.is_red != top.is_red and prev_parent.value == top.value + 1:
can_use_exposed = self.can_move_to_foundation(
prev_parent, self.foundation_index_for_suit(prev_parent.suit)
) or any(
c_i != src_col and c_i != dst_col and self.can_move_to_tableau([prev_parent], c_i)
for c_i in range(self.NUM_TABLEAU)
)
if not can_use_exposed:
continue
return True
return False
def get_hint(self) -> dict | None:
# 1. Direkt auf Foundation
for fc_i, c in enumerate(self.freecells):
if c is not None:
f_idx = self.foundation_index_for_suit(c.suit)
if self.can_move_to_foundation(c, f_idx):
return {"type": "fc_to_foundation", "src_cell": fc_i, "dst": f_idx}
for col_i, col in enumerate(self.tableau):
if col:
c = col[-1]
f_idx = self.foundation_index_for_suit(c.suit)
if self.can_move_to_foundation(c, f_idx):
return {"type": "tab_to_foundation", "src_col": col_i, "dst": f_idx}
# 2. FreeCell zurück ins Tableau auf passende Karte
for fc_i, c in enumerate(self.freecells):
if c is not None:
for dst_col in range(self.NUM_TABLEAU):
if self.tableau[dst_col] and self.can_move_to_tableau([c], dst_col):
return {"type": "fc_to_tableau", "src_cell": fc_i, "dst_col": dst_col}
# 3. Geordneten Run im Tableau auf eine nicht-leere Zielspalte legen (verlängert Sequenz / legt frei)
for src_col, col in enumerate(self.tableau):
if not col:
continue
# Längsten geordneten Run ab Spaltenende bestimmen
run_start = len(col) - 1
while run_start > 0 and is_alternating_descending(col[run_start - 1 :]):
run_start -= 1
moving = col[run_start:]
for dst_col in range(self.NUM_TABLEAU):
if src_col != dst_col and self.tableau[dst_col] and self.can_move_to_tableau(moving, dst_col):
return {
"type": "tab_to_tableau",
"src_col": src_col,
"card_idx": run_start,
"dst_col": dst_col,
}
# 4. In leere Tableau-Spalte auslagern (wenn dadurch Karten darunter frei werden)
empty_cols = [i for i, col in enumerate(self.tableau) if not col]
if empty_cols:
dst_empty = empty_cols[0]
for src_col, col in enumerate(self.tableau):
if len(col) <= 1:
continue
run_start = len(col) - 1
while run_start > 0 and is_alternating_descending(col[run_start - 1 :]):
run_start -= 1
if run_start > 0 and self.can_move_to_tableau(col[run_start:], dst_empty):
return {
"type": "tab_to_tableau",
"src_col": src_col,
"card_idx": run_start,
"dst_col": dst_empty,
}
# 5. Karte in freie Zelle parken (bevorzugt Spalten, in denen direkt darunter ein Ass/niedriger Wert liegt)
free_cell = self.first_empty_freecell()
if free_cell is not None:
best_col: int | None = None
best_val = 99
for col_i, col in enumerate(self.tableau):
if len(col) >= 2 and col[-2].value < best_val:
best_val = col[-2].value
best_col = col_i
if best_col is None:
best_col = next((i for i, col in enumerate(self.tableau) if col), None)
if best_col is not None:
return {"type": "tab_to_fc", "src_col": best_col, "dst_cell": free_cell}
return None
# --- Persistenz ---
def serialize_board(self) -> dict:
return {
"difficulty": self.difficulty,
"freecells": [c.to_dict() if c is not None else None for c in self.freecells],
"foundations": [[c.to_dict() for c in f] for f in self.foundations],
"tableau": [[c.to_dict() for c in col] for col in self.tableau],
}
def restore_board(self, board: dict):
self.difficulty = max(0, min(3, int(board.get("difficulty", 1))))
self.freecells = [
SolitaireCard.from_dict(d) if d is not None else None
for d in board["freecells"]
]
self.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"]
]

View File

@ -0,0 +1,397 @@
# -*- coding: utf-8 -*-
# games/solitaire/freecell/models/freecell_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 SUITS
_IS_RED = tuple((c // 13) in (1, 2) for c in range(52))
_SUIT = tuple(c // 13 for c in range(52))
_VAL = tuple((c % 13) + 1 for c in range(52))
@dataclass
class FreeCellSolveReport:
solvable: bool
nodes_expanded: int
backtracks: 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 _deal_columns_from_deck(deck_ids: list[int]) -> list[list[int]]:
cols: list[list[int]] = [[] for _ in range(8)]
for idx, cid in enumerate(deck_ids):
cols[idx % 8].append(cid)
return cols
def evaluate_freecell_hardness(cols: list[list[int]]) -> float:
"""
Bewertet die strukturelle Schwierigkeit einer FreeCell-Startauslage:
- Tief vergrabene Asse/Zweien (ganz oben in den 7er-/6er-Spalten) erhöhen den Wert stark.
- Hohe Karten, die unterhalb niedrigerer Karten liegen (Inversionen), erhöhen den Wert.
- Bereits natürlich geordnete Paare senken den Wert.
"""
score = 0.0
for col in cols:
n = len(col)
for pos, cid in enumerate(col):
depth_from_bottom = n - 1 - pos
v = _VAL[cid]
if v == 1:
score += depth_from_bottom * 4.2
elif v == 2:
score += depth_from_bottom * 2.6
elif v == 3:
score += depth_from_bottom * 1.2
if pos < n - 1:
below = col[pos + 1]
if _IS_RED[cid] != _IS_RED[below] and _VAL[cid] == _VAL[below] + 1:
score -= 3.5
elif _VAL[cid] < _VAL[below]:
score += 1.4
# Direkte Startzüge zwischen den 8 unteren Spitzen zählen
bottoms = [c[-1] for c in cols if c]
natural_moves = 0
for i, ca in enumerate(bottoms):
if _VAL[ca] == 1:
score -= 6.0
for j, cb in enumerate(bottoms):
if i != j and _IS_RED[ca] != _IS_RED[cb] and _VAL[ca] + 1 == _VAL[cb]:
natural_moves += 1
score -= natural_moves * 2.8
return score
def _safe_auto_promote(
found: list[int],
freecells: list[int],
cols: list[list[int]],
) -> None:
"""Legt Karten sicher auf die Foundation, sobald keine Gegenfarben-Karte sie mehr zum Bauen braucht."""
changed = True
while changed:
changed = False
min_black = min(found[0], found[3])
min_red = min(found[1], found[2])
for idx, cid in enumerate(freecells):
if cid < 0:
continue
s, v = _SUIT[cid], _VAL[cid]
if v == found[s] + 1:
opp_min = min_black if _IS_RED[cid] else min_red
if v <= 2 or v <= opp_min + 1:
freecells[idx] = -1
found[s] += 1
changed = True
break
if changed:
continue
for col in cols:
if not col:
continue
cid = col[-1]
s, v = _SUIT[cid], _VAL[cid]
if v == found[s] + 1:
opp_min = min_black if _IS_RED[cid] else min_red
if v <= 2 or v <= opp_min + 1:
col.pop()
found[s] += 1
changed = True
break
def _state_key(
found: tuple[int, ...],
freecells: tuple[int, ...],
cols: tuple[tuple[int, ...], ...],
) -> tuple:
# Freie Zellen und Spalten sind untereinander symmetrisch -> Sortieren kollabiert Duplikate enorm
return (found, tuple(sorted(freecells)), tuple(sorted(cols)))
def _ordered_tail_len(col: tuple[int, ...]) -> int:
if not col:
return 0
length = 1
for i in range(len(col) - 1, 0, -1):
lower = col[i]
upper = col[i - 1]
if _IS_RED[upper] != _IS_RED[lower] and _VAL[upper] == _VAL[lower] + 1:
length += 1
else:
break
return length
def solve_freecell_deal(deck_ids: list[int], max_nodes: int = 4200) -> FreeCellSolveReport:
cols_init = _deal_columns_from_deck(deck_ids)
hardness = evaluate_freecell_hardness(cols_init)
found_init = [0, 0, 0, 0]
fc_init = [-1, -1, -1, -1]
_safe_auto_promote(found_init, fc_init, cols_init)
if sum(found_init) == 52:
return FreeCellSolveReport(True, 1, 0, hardness)
start_state = (
tuple(found_init),
tuple(fc_init),
tuple(tuple(c) for c in cols_init),
)
visited: set[tuple] = {_state_key(*start_state)}
pq: list[tuple[int, int, int, tuple]] = []
counter = 0
def heuristic(st: tuple) -> int:
fnd, fcs, cls = st
remaining = 52 - sum(fnd)
occupied_fc = sum(1 for x in fcs if x >= 0)
empty_cols = sum(1 for c in cls if not c)
disorder = 0
for c in cls:
for k in range(len(c) - 1):
if not (_IS_RED[c[k]] != _IS_RED[c[k + 1]] and _VAL[c[k]] == _VAL[c[k + 1]] + 1):
disorder += 1
return remaining * 5 + disorder * 4 + occupied_fc * 3 - empty_cols * 4
heapq.heappush(pq, (heuristic(start_state), 0, counter, start_state))
nodes = 0
backtracks = 0
best_found = sum(found_init)
while pq and nodes < max_nodes:
_prio, depth, _tie, state = heapq.heappop(pq)
fnd, fcs, cls = state
nodes += 1
f_sum = sum(fnd)
if f_sum == 52:
return FreeCellSolveReport(True, nodes, backtracks, hardness)
if f_sum > best_found:
best_found = f_sum
elif f_sum < best_found - 2:
backtracks += 1
# Sind alle Spalten bereits streng absteigend sortiert, ist das Spiel gewonnen
if all(_ordered_tail_len(c) == len(c) for c in cls):
only_descending = True
for c in cls:
for k in range(len(c) - 1):
if _VAL[c[k]] < _VAL[c[k + 1]]:
only_descending = False
break
if only_descending and f_sum >= 36:
return FreeCellSolveReport(True, nodes, backtracks, hardness)
free_fc_count = sum(1 for x in fcs if x < 0)
empty_col_indices = [i for i, c in enumerate(cls) if not c]
empty_col_count = len(empty_col_indices)
next_states: list[tuple] = []
def push_cand(nf: list[int], nfc: list[int], ncls: list[list[int]]):
_safe_auto_promote(nf, nfc, ncls)
cand = (tuple(nf), tuple(nfc), tuple(tuple(c) for c in ncls))
k = _state_key(*cand)
if k not in visited:
visited.add(k)
next_states.append(cand)
# 1. Explizite Foundation-Züge (FreeCell & Spaltenspitzen)
for fc_i, cid in enumerate(fcs):
if cid >= 0 and _VAL[cid] == fnd[_SUIT[cid]] + 1:
nf, nfc, ncls = list(fnd), list(fcs), [list(c) for c in cls]
nfc[fc_i] = -1
nf[_SUIT[cid]] += 1
push_cand(nf, nfc, ncls)
for col_i, col in enumerate(cls):
if col:
cid = col[-1]
if _VAL[cid] == fnd[_SUIT[cid]] + 1:
nf, nfc, ncls = list(fnd), list(fcs), [list(c) for c in cls]
ncls[col_i].pop()
nf[_SUIT[cid]] += 1
push_cand(nf, nfc, ncls)
# 2. FreeCell -> Tableau (belegte Spalten + max. eine leere Spalte)
seen_fc_cards: set[int] = set()
for fc_i, cid in enumerate(fcs):
if cid < 0 or cid in seen_fc_cards:
continue
seen_fc_cards.add(cid)
used_empty = False
for dst_i, dst_col in enumerate(cls):
if not dst_col:
if used_empty:
continue
used_empty = True
else:
top = dst_col[-1]
if _IS_RED[top] == _IS_RED[cid] or _VAL[top] != _VAL[cid] + 1:
continue
nf, nfc, ncls = list(fnd), list(fcs), [list(c) for c in cls]
nfc[fc_i] = -1
ncls[dst_i].append(cid)
push_cand(nf, nfc, ncls)
# 3. Tableau -> Tableau (inkl. Supermoves über freie Zellen & leere Hilfsspalten)
for src_i, src_col in enumerate(cls):
if not src_col:
continue
tail_max = _ordered_tail_len(src_col)
used_empty_for_src = False
for dst_i, dst_col in enumerate(cls):
if src_i == dst_i:
continue
if not dst_col:
if used_empty_for_src:
continue
aux_empty = max(0, empty_col_count - 1)
max_cap = (free_fc_count + 1) * (1 << aux_empty)
# Ganzen Run in leere Spalte schieben bringt nichts, wenn nichts darunter freigelegt wird
max_useful = min(tail_max, max_cap, len(src_col) - 1)
if max_useful <= 0:
continue
used_empty_for_src = True
# Bevorzuge das Freilegen des kompletten geordneten Runs
nf, nfc, ncls = list(fnd), list(fcs), [list(c) for c in cls]
moving = ncls[src_i][-max_useful:]
del ncls[src_i][-max_useful:]
ncls[dst_i].extend(moving)
push_cand(nf, nfc, ncls)
else:
dst_top = dst_col[-1]
max_cap = (free_fc_count + 1) * (1 << empty_col_count)
limit = min(tail_max, max_cap)
# Genau eine Länge k im geordneten Tail kann wertmäßig auf dst_top passen!
needed_val = _VAL[dst_top] - 1
head_idx = len(src_col) - limit
for idx in range(head_idx, len(src_col)):
cand_head = src_col[idx]
if _VAL[cand_head] == needed_val and _IS_RED[cand_head] != _IS_RED[dst_top]:
nf, nfc, ncls = list(fnd), list(fcs), [list(c) for c in cls]
moving = ncls[src_i][idx:]
del ncls[src_i][idx:]
ncls[dst_i].extend(moving)
push_cand(nf, nfc, ncls)
break
# 4. Tableau-Spitze -> erste freie FreeCell
if free_fc_count > 0:
first_empty_fc = fcs.index(-1)
for src_i, src_col in enumerate(cls):
if not src_col:
continue
nf, nfc, ncls = list(fnd), list(fcs), [list(c) for c in cls]
nfc[first_empty_fc] = ncls[src_i].pop()
push_cand(nf, nfc, ncls)
for ns in next_states:
if sum(ns[0]) == 52:
return FreeCellSolveReport(True, nodes, backtracks, hardness)
counter += 1
heapq.heappush(pq, (heuristic(ns), depth + 1, counter, ns))
return FreeCellSolveReport(False, nodes, backtracks, hardness)
def generate_solvable_freecell_columns(
difficulty: int = 1,
seed: int | None = None,
) -> list[list[SolitaireCard]]:
"""
Erzeugt 8 garantiert lösbare FreeCell-Spalten passend zur gewählten Schwierigkeitsstufe (0..3).
"""
rng = random.Random(seed) if seed is not None else random.Random()
diff = max(0, min(3, int(difficulty)))
target_scores = {
0: 28.0, # Leicht: niedrige Karten früh frei, kaum Blockaden
1: 68.0, # Normal: klassisches FreeCell-Gefühl
2: 108.0, # Schwer: vergrabene Asse, engere Zell-Kapazität
3: 155.0, # Gottheit: maximale Verzahnung & Backtracking
}
target = target_scores[diff]
hardness_bounds = {
0: (-80.0, 48.0),
1: (38.0, 86.0),
2: (72.0, 130.0),
3: (92.0, 999.0),
}
h_min, h_max = hardness_bounds[diff]
max_attempts = 200
node_budget = 2600 if diff <= 1 else 4500
desired_pool = 2 if diff <= 1 else 3
solvable_candidates: list[tuple[float, list[int]]] = []
base_deck = list(range(52))
for attempt in range(max_attempts):
trial = list(base_deck)
rng.shuffle(trial)
cols_preview = _deal_columns_from_deck(trial)
h_val = evaluate_freecell_hardness(cols_preview)
if attempt < int(max_attempts * 0.70) and not (h_min <= h_val <= h_max):
continue
report = solve_freecell_deal(trial, max_nodes=node_budget)
if not report.solvable:
continue
composite = report.layout_hardness + (report.nodes_expanded / 32.0) + (report.backtracks * 1.5)
solvable_candidates.append((composite, trial))
if diff == 0 and composite <= 36.0:
break
if diff == 1 and 50.0 <= composite <= 84.0:
break
if diff == 2 and composite >= 96.0:
break
if diff == 3 and composite >= 128.0:
break
if len(solvable_candidates) >= desired_pool:
break
while not solvable_candidates:
trial = list(base_deck)
rng.shuffle(trial)
report = solve_freecell_deal(trial, max_nodes=5000)
if report.solvable:
composite = report.layout_hardness + (report.nodes_expanded / 32.0)
solvable_candidates.append((composite, trial))
if diff == 3:
best_deck = max(solvable_candidates, key=lambda x: x[0])[1]
elif diff == 0:
best_deck = min(solvable_candidates, key=lambda x: x[0])[1]
else:
best_deck = min(solvable_candidates, key=lambda x: abs(x[0] - target))[1]
raw_cols = _deal_columns_from_deck(best_deck)
return [[_decode_card(cid) for cid in col] for col in raw_cols]

View File

@ -0,0 +1,12 @@
# -*- coding: utf-8 -*-
# games/solitaire/freecell/start.py
from games.solitaire.freecell.views.freecell_menu_view import FreeCellMenuView
from resources.code_res.game_constants import CAT_SOLO
GAME_TITLE_KEY = "game_title_freecell"
GAME_FOLDER_ID = "solitaire/freecell"
GAME_CATEGORY = CAT_SOLO
def start_game(context):
FreeCellMenuView(context).show(ask_resume_popup=True)

View File

@ -0,0 +1,39 @@
# -*- coding: utf-8 -*-
# games/solitaire/freecell/views/freecell_menu_view.py
from __future__ import annotations
from games.solitaire.base.solitaire_menu_base import SolitaireMenuBase
from games.solitaire.freecell.views.freecell_table_view import FreeCellTableView
from resources.code_res.game_constants import FREECELL_VARIANTS
GAME_FOLDER_ID = "solitaire/freecell"
GAME_TITLE_KEY = "game_title_freecell"
class FreeCellMenuView(SolitaireMenuBase):
GAME_FOLDER_ID = GAME_FOLDER_ID
GAME_TITLE_KEY = GAME_TITLE_KEY
TOPBAR_KEY = "fc_menu_topbar"
SUBTITLE_KEY = "fc_menu_subtitle"
CONTROLS_HINT_KEY = "fc_controls_hint"
DIFF_SETTING_PREFIX = "freecell_diff"
DEFAULT_VARIANT_KEY = "freecell_std"
REQUIRED_BOARD_KEYS = ("tableau", "freecells")
MODE_LABEL_KEY = "fc_variant_info_lbl"
DESC_KEY_PREFIX = "fc_desc_"
def _variants_dict(self) -> dict[str, dict]:
return FREECELL_VARIANTS
def _launch_table_view(
self, variant_key: str, difficulty: int, resume_state_json: str | None = None
) -> None:
FreeCellTableView(
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,
)

View File

@ -0,0 +1,398 @@
# -*- coding: utf-8 -*-
# games/solitaire/freecell/views/freecell_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.freecell.models.freecell_engine import FreeCellEngine
from resources.code_res.game_constants import (
ACCENT_GOLD,
ACCENT_GOTH,
FREECELL_VARIANTS,
RED_SUITS,
SUBTLE_BORDER,
SUIT_SYMBOLS,
SUITS,
)
from resources.code_res.i18n import t
GAME_FOLDER_ID = "solitaire/freecell"
GAME_TITLE_KEY = "game_title_freecell"
class FreeCellTableView(SolitaireTableController):
GAME_FOLDER_ID = GAME_FOLDER_ID
HAS_AUTOCOMPLETE_BTN = True
AUTO_STEP_DELAY_MS = 10
AUTO_FLIGHT_MS = 70
SPEED_THRESHOLDS_SEC = (180, 330)
DRAG_STACK_DY_FACTOR = 0.205
def __init__(
self,
context,
variant_key: str = "freecell_std",
difficulty: int = 1,
on_back_to_menu=None,
resume_state_json: str | None = None,
):
v_key = variant_key if variant_key in FREECELL_VARIANTS else "freecell_std"
cfg = FREECELL_VARIANTS[v_key]
self._init_controller_state(context, v_key, cfg, difficulty, on_back_to_menu)
self._fc_x: list[int] = [0] * 4
self._found_x: list[int] = [0] * 4
self._col_x: list[int] = [0] * 8
self._top_y: int = 16
self._tableau_y: int = 186
self._tableau_card_rects: list[list[tuple[int, int, int, int]]] = [[] for _ in range(8)]
if resume_state_json:
self.engine = FreeCellEngine.__new__(FreeCellEngine)
super(FreeCellEngine, self.engine).__init__()
self.engine.difficulty = self.difficulty
self.engine.seed = None
self.engine.freecells = [None] * 4
self.engine.foundations = [[] for _ in range(4)]
self.engine.tableau = [[] for _ in range(8)]
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 = FreeCellEngine(difficulty=self.difficulty)
self._finish_startup(is_resumed=bool(resume_state_json))
def _reset_engine_for_new_deal(self):
self.engine.new_game(difficulty=self.difficulty)
def _compute_tableau_ys(self, count: int) -> list[int]:
if count <= 0:
return []
_cw, ch = self.card_size
avail_h = max(180, max(420, self.canvas.winfo_height()) - self._tableau_y - self._frame_bot_pad)
step_cnt = max(0, count - 1)
up_dy = max(16, int(ch * 0.205))
if step_cnt > 0 and (step_cnt * up_dy + ch) > avail_h:
up_dy = max(12, int((avail_h - ch) / step_cnt))
return [self._tableau_y + i * up_dy for i in range(count)]
def _snapshot_card_positions(self) -> dict[tuple[str, str, int], tuple[int, int]]:
pos: dict[tuple[str, str, int], tuple[int, int]] = {}
for fc_i, c in enumerate(self.engine.freecells):
if c is not None:
pos[self._card_key(c)] = (self._fc_x[fc_i], self._top_y)
for f_idx in range(4):
fx = self._found_x[f_idx]
for c in self.engine.foundations[f_idx]:
pos[self._card_key(c)] = (fx, self._top_y)
for col_idx in range(8):
tx = self._col_x[col_idx]
col = self.engine.tableau[col_idx]
for c, cy in zip(col, self._compute_tableau_ys(len(col))):
pos[self._card_key(c)] = (tx, cy)
return pos
def _ordered_moved_cards(self, moved_keys: set[tuple[str, str, int]]) -> list[SolitaireCard]:
ordered: list[SolitaireCard] = []
for c in self.engine.freecells:
if c is not None and self._card_key(c) in moved_keys:
ordered.append(c)
for pile in (*self.engine.foundations, *self.engine.tableau):
for c in pile:
if self._card_key(c) in moved_keys:
ordered.append(c)
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)
self._frame_bot_pad = bot_pad
usable_w = cw - 2 * margin_x
gap_x = max(10, int(usable_w * 0.015))
center_extra = max(16, int(gap_x * 1.8))
row_gap = max(16, int(ch * 0.030))
card_w_by_w = int((usable_w - 6 * gap_x - center_extra) / 8)
card_w_by_h = int(round((max(220, ch - top_pad - row_gap - bot_pad) / 3.00) / aspect))
card_w = max(62, min(card_w_by_w, card_w_by_h))
card_h = int(round(card_w * aspect))
self.card_size = (card_w, card_h)
top_total_w = 8 * card_w + 6 * gap_x + center_extra
top_start_x = max(margin_x, (cw - top_total_w) // 2)
self._fc_x = [top_start_x + i * (card_w + gap_x) for i in range(4)]
found_start_x = self._fc_x[3] + card_w + center_extra
self._found_x = [found_start_x + i * (card_w + gap_x) for i in range(4)]
tab_gap = (top_total_w - 8 * card_w) / 7.0
self._col_x = [int(round(top_start_x + i * (card_w + tab_gap))) for i in range(8)]
self._top_y = top_pad
self._tableau_y = self._top_y + card_h + row_gap
self.redraw()
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()
valid_drag_fc: set[int] = set()
valid_drag_found: set[int] = set()
valid_drag_tab: set[int] = set()
if self._dragging and self._press_info:
d_cards: list[SolitaireCard] = self._press_info["cards"]
if len(d_cards) == 1:
valid_drag_fc = {i for i in range(4) if self.engine.can_move_to_freecell(i)}
valid_drag_found = {i for i in range(4) if self.engine.can_move_to_foundation(d_cards[0], i)}
for t_i in range(8):
if not (self._press_info.get("zone") == "tableau" and self._press_info.get("col") == t_i):
if self.engine.can_move_to_tableau(d_cards, t_i):
valid_drag_tab.add(t_i)
hint = self._active_hint
for fc_i in range(4):
fx = self._fc_x[fc_i]
fc_hl = ACCENT_GOTH if fc_i in valid_drag_fc else None
if hint and (
(hint.get("src_cell") == fc_i and hint.get("type") in ("fc_to_foundation", "fc_to_tableau"))
or (hint.get("dst_cell") == fc_i and hint.get("type") == "tab_to_fc")
):
fc_hl = ACCENT_GOLD
self._draw_slot(fx, self._top_y, symbol="◇", symbol_color=SUBTLE_BORDER, highlight_color=fc_hl)
c = self.engine.freecells[fc_i]
if exclude_source and exclude_source.get("zone") == "freecell" and exclude_source.get("col") == fc_i:
c = None
if c is not None and self._card_key(c) not in hidden:
self._draw_card_at(c, fx, self._top_y, tags=(f"fc_cell_{fc_i}",), highlight_color=fc_hl)
for f_idx, suit in enumerate(SUITS):
fx = self._found_x[f_idx]
f_hl = ACCENT_GOTH if f_idx in valid_drag_found else None
if hint and hint.get("dst") == f_idx and "foundation" in hint.get("type", ""):
f_hl = ACCENT_GOLD
self._draw_slot(
fx, self._top_y, symbol=SUIT_SYMBOLS[suit],
symbol_color="#8c3b4a" if suit in RED_SUITS else "#635a73", highlight_color=f_hl,
)
pile = list(self.engine.foundations[f_idx])
if exclude_source and exclude_source.get("zone") == "foundation" and exclude_source.get("col") == f_idx and pile:
pile = pile[:-1]
pile = [c for c in pile if self._card_key(c) not in hidden]
if pile:
self._draw_card_at(pile[-1], fx, self._top_y, tags=(f"fc_found_{f_idx}",), highlight_color=f_hl)
self._tableau_card_rects = [[] for _ in range(8)]
for col_idx in range(8):
tx = self._col_x[col_idx]
full_col = list(self.engine.tableau[col_idx])
if exclude_source and exclude_source.get("zone") == "tableau" and exclude_source.get("col") == col_idx:
full_col = full_col[: exclude_source["idx"]]
cards = [c for c in full_col if self._card_key(c) not in hidden]
slot_hl = ACCENT_GOTH if (not cards and col_idx in valid_drag_tab) else None
if not cards and hint and hint.get("dst_col") == col_idx:
slot_hl = ACCENT_GOLD
self._draw_slot(tx, self._tableau_y, highlight_color=slot_hl)
if not cards:
continue
ys = self._compute_tableau_ys(len(cards))
for c_idx, (card, cur_y) in enumerate(zip(cards, ys)):
is_last = (c_idx == len(cards) - 1)
c_hl = ACCENT_GOTH if (is_last and col_idx in valid_drag_tab) else None
if hint:
if hint.get("src_col") == col_idx and (
(hint.get("type") in ("tab_to_foundation", "tab_to_fc") and is_last)
or (hint.get("type") == "tab_to_tableau" and c_idx >= hint.get("card_idx", 99))
):
c_hl = ACCENT_GOLD
elif hint.get("dst_col") == col_idx and is_last:
c_hl = ACCENT_GOLD
self._draw_card_at(card, tx, cur_y, tags=(f"fc_tab_{col_idx}_{c_idx}",), highlight_color=c_hl)
next_y = ys[c_idx + 1] if not is_last else (cur_y + ch)
self._tableau_card_rects[col_idx].append((tx, cur_y, tx + cw, next_y))
self._finish_canvas_frame(canvas_w, canvas_h, exclude_source, hidden)
def _hover_card_probe(self, x: int, y: int) -> dict | None:
cw, ch = self.card_size
for fc_i in range(4):
fx = self._fc_x[fc_i]
if fx <= x <= fx + cw and self._top_y <= y <= self._top_y + ch:
c = self.engine.freecells[fc_i]
return {"card": c, "x": fx, "y": self._top_y, "size": self.card_size, "under_tag": None} if (c and c.face_up) else None
for f_idx in range(4):
fx = self._found_x[f_idx]
if fx <= x <= fx + cw and self._top_y <= y <= self._top_y + ch:
pile = self.engine.foundations[f_idx]
return {"card": pile[-1], "x": fx, "y": self._top_y, "size": self.card_size, "under_tag": None} if (pile and pile[-1].face_up) else None
for col_idx in range(8):
rects, col_cards = self._tableau_card_rects[col_idx], self.engine.tableau[col_idx]
for c_idx in range(len(rects) - 1, -1, -1):
if c_idx >= len(col_cards):
continue
x1, y1, x2, y2 = rects[c_idx]
if x1 <= x <= x2 and y1 <= y <= y2:
card = col_cards[c_idx]
if not card.face_up:
return None
next_tag = f"fc_tab_{col_idx}_{c_idx + 1}" if (c_idx + 1) < len(col_cards) else None
return {"card": card, "x": x1, "y": y1, "size": self.card_size, "under_tag": next_tag}
return None
def _hit_test(self, x: int, y: int) -> dict | None:
cw, ch = self.card_size
for fc_i in range(4):
fx = self._fc_x[fc_i]
if fx <= x <= fx + cw and self._top_y <= y <= self._top_y + ch:
c = self.engine.freecells[fc_i]
return {"zone": "freecell", "col": fc_i, "cards": [c], "origin": (fx, self._top_y)} if c else None
for f_idx in range(4):
fx = self._found_x[f_idx]
if fx <= x <= fx + cw and self._top_y <= y <= self._top_y + ch:
pile = self.engine.foundations[f_idx]
return {"zone": "foundation", "col": f_idx, "cards": [pile[-1]], "origin": (fx, self._top_y)} if pile else None
for col_idx in range(8):
rects, col_cards = self._tableau_card_rects[col_idx], self.engine.tableau[col_idx]
for c_idx in range(len(rects) - 1, -1, -1):
if c_idx >= len(col_cards):
continue
x1, y1, x2, y2 = rects[c_idx]
if x1 <= x <= x2 and y1 <= y <= y2:
if not self.engine.can_grab_tableau_stack(col_idx, c_idx):
return None
return {"zone": "tableau", "col": col_idx, "idx": c_idx, "cards": col_cards[c_idx:], "origin": (x1, y1)}
return None
def _handle_click(self, info: dict):
self._dispatch_tap_or_double_click(info)
def _smart_auto_move(self, info: dict):
zone, cards = info.get("zone"), info.get("cards", [])
if not cards:
return
capacity_blocked_max: int | None = None
def attempt_move() -> bool:
nonlocal capacity_blocked_max
if len(cards) == 1:
if zone == "freecell" and self.engine.move_freecell_to_foundation(info["col"]):
return True
if zone == "tableau":
sc = info["col"]
if info["idx"] == len(self.engine.tableau[sc]) - 1 and self.engine.move_tableau_to_foundation(sc):
return True
src_col = info.get("col", -1) if zone == "tableau" else -1
skip_empty = (zone == "tableau" and info.get("idx") == 0)
non_empty = [c for c in range(8) if c != src_col and self.engine.tableau[c]]
empty = [] if skip_empty else [c for c in range(8) if c != src_col and not self.engine.tableau[c]]
for dst_col in non_empty + empty:
ok, reason = self.engine.check_tableau_drop(cards, dst_col)
if not ok:
if reason == "capacity":
capacity_blocked_max = self.engine.max_movable_cards(
target_is_empty_tableau=(len(self.engine.tableau[dst_col]) == 0)
)
continue
if zone == "freecell" and self.engine.move_freecell_to_tableau(info["col"], dst_col):
return True
if zone == "tableau" and self.engine.move_tableau_to_tableau(src_col, info["idx"], dst_col):
return True
if zone == "foundation" and self.engine.move_foundation_to_tableau(info["col"], dst_col):
return True
if zone == "tableau" and len(cards) == 1 and self.engine.move_tableau_to_freecell(info["col"]):
return True
return False
if self._run_animated_action(attempt_move, duration_ms=120, after_cb=self._after_player_move):
self.ctx.sounds.play("click")
elif capacity_blocked_max is not None:
self.status_var.set(t("fc_supermove_limit_msg", len(cards), capacity_blocked_max))
def _try_drop(self, info: dict, drop_x: int, drop_y: int) -> bool:
cw, ch = self.card_size
cx, cy = drop_x + cw // 2, drop_y + ch // 2
zone, cards = info["zone"], info["cards"]
if len(cards) == 1 and cy < self._tableau_y + 15:
best_fc, best_fc_dist = None, 999999
for fc_i in range(4):
fx, fy = self._fc_x[fc_i] + cw // 2, self._top_y + ch // 2
if abs(cx - fx) <= int(cw * 0.72) and abs(cy - fy) <= int(ch * 0.80):
dist = abs(cx - fx) + abs(cy - fy)
if dist < best_fc_dist and self.engine.can_move_to_freecell(fc_i):
best_fc, best_fc_dist = fc_i, dist
if best_fc is not None:
if zone == "tableau":
return self.engine.move_tableau_to_freecell(info["col"], best_fc)
if zone == "freecell":
return self.engine.move_freecell_to_freecell(info["col"], best_fc)
if zone == "foundation":
return self.engine.move_foundation_to_freecell(info["col"], best_fc)
best_f, best_f_dist = None, 999999
for f_idx in range(4):
fx, fy = self._found_x[f_idx] + cw // 2, self._top_y + ch // 2
if abs(cx - fx) <= int(cw * 0.72) and abs(cy - fy) <= int(ch * 0.80):
dist = abs(cx - fx) + abs(cy - fy)
if dist < best_f_dist and self.engine.can_move_to_foundation(cards[0], f_idx):
best_f, best_f_dist = f_idx, dist
if best_f is not None:
if zone == "freecell":
return self.engine.move_freecell_to_foundation(info["col"], best_f)
if zone == "tableau":
return self.engine.move_tableau_to_foundation(info["col"], best_f)
best_col, best_dx = None, 999999
capacity_exceeded_limit: int | None = None
for col_idx in range(8):
if zone == "tableau" and info["col"] == col_idx:
continue
dx = abs(cx - (self._col_x[col_idx] + cw // 2))
if dx <= int(cw * 0.72) and cy >= self._tableau_y - int(ch * 0.35):
ok, reason = self.engine.check_tableau_drop(cards, col_idx)
if ok and dx < best_dx:
best_col, best_dx = col_idx, dx
elif reason == "capacity":
capacity_exceeded_limit = self.engine.max_movable_cards(
target_is_empty_tableau=(len(self.engine.tableau[col_idx]) == 0)
)
if best_col is not None:
if zone == "freecell":
return self.engine.move_freecell_to_tableau(info["col"], best_col)
if zone == "tableau":
return self.engine.move_tableau_to_tableau(info["col"], info["idx"], best_col)
if zone == "foundation":
return self.engine.move_foundation_to_tableau(info["col"], best_col)
if capacity_exceeded_limit is not None:
self.status_var.set(t("fc_supermove_limit_msg", len(cards), capacity_exceeded_limit))
return False

View File

@ -0,0 +1,58 @@
# Klondike Solitaire (`games/solitaire/klondike`)
Die klassische Patience auf sieben Tableau-Spalten – erweitert um Vorab-Lösbarkeitsprüfung, vier Schwierigkeitsstufen, flüssige Kartenflug-Animationen und eine Schutzmechanik gegen endlose Stapel-Durchläufe.
---
## Spielvarianten
| Variante (`variant_key`) | Modus | Kartenrücken | Basis-XP |
| :--- | :--- | :---: | :---: |
| `klondike_1` | **1 Karte ziehen** vom Nachziehstapel | Schwarz (`Back_Black.png`) | $\times 1.00$ |
| `klondike_3` | **3er-Fächer ziehen** vom Nachziehstapel | Rot (`Back_Red.png`) | $\times 1.35$ |
---
## Spielregeln & Besonderheiten
1. **Aufbau:** 52 Karten. $28$ Karten liegen auf $7$ Tableau-Spalten ($1$ bis $7$ Karten pro Spalte, jeweils die oberste Karte offen), $24$ Karten bilden den verdeckten Nachziehstapel (*Stock*) oben links.
2. **Tableau:** Gebaut wird in absteigender Reihenfolge mit wechselnden Farben (Rot auf Schwarz / Schwarz auf Rot). In leere Spalten dürfen ausschließlich **Könige** (einzeln oder als Kopf einer gültigen Kette) gelegt werden.
3. **Ablagestapel (Foundations):** Oben rechts werden alle vier Farben (`♣`, `♦`, `♥`, `♠`) aufsteigend von **Ass (`A`) bis König (`K`)** gesammelt.
4. **Nachziehstapel & Stagnations-Sperre:**
* Im Modus `klondike_3` ist auf der Stufe **Gottheit** die Anzahl der Stapel-Neuauflagen (*Redeals*) auf $3$ begrenzt.
* Wird der komplette Nachziehstapel **$3$ Zyklen infolge** durchgeklickt, ohne dass sich auf dem Spielfeld etwas verändert hat, wird der Stapel gesperrt (rotes `✕`-Symbol). Über `Strg+Z` oder `⟲ Anfang` lässt sich die Sperre jederzeit wieder auflösen.
5. **Auto-Ende (`⚡ Auto-Ende`):** Sobald Nachzieh- und Ablagestapel leer sind und alle Tableau-Karten offen liegen, kann der Rest der Partie automatisch animiert abgeräumt werden.
---
## Solver & Schwierigkeitsgrade (`klondike_solver.py`)
Vor jedem Spielstart bewertet und löst der integrierte Solver Kandidaten-Decks, sodass keine unlösbaren Verteilungen ausgegeben werden:
* Strukturelle Härtefaktoren wie tief verdeckte Asse/Zweien, gleichfarbige Blockaden und fehlende Start-Könige fließen zusammen mit den benötigten Suchknoten in das Schwierigkeitsprofil (`0` *Leicht* bis `3` *Gottheit*) ein.
---
## Erfahrungspunkte & Speed-Bonus
Der kombinierte Multiplikator berechnet sich aus Varianten-Faktor, Schwierigkeitsstufe und Spielzeit $t$:
$$\text{Mult}_{\text{gesamt}} = \text{Mult}_{\text{Variante}} \cdot \text{Mult}_{\text{Stufe}} \cdot \text{Bonus}_{\text{Zeit}}(t)$$
* **Voller Speed-Bonus ($\times 1.25$):** Sieg in $t \le 180\,\text{s}$ ($3{:}00$ Min.)
* **Kleiner Speed-Bonus ($\times 1.12$):** Sieg in $180\,\text{s} < t \le 330\,\text{s}$ ($5{:}30$ Min.)
* **Standard ($\times 1.00$):** Sieg in $t > 330\,\text{s}$
---
## Dateistruktur
```text
games/solitaire/klondike/
├── start.py # Einstiegspunkt & Kategorie-Registrierung (CAT_SOLO)
├── models/
│ ├── klondike_solver.py # Lösbarkeits-Prüfung & Schwierigkeits-Klassifizierung
│ └── klondike_engine.py # Spielregeln, Punktewertung, Stagnations-Check & Hints
└── views/
├── klondike_menu_view.py # Varianten-Umschalter, Schwierigkeitswahl & Resume-Modal
└── klondike_table_view.py # 7-Spalten-Canvas, Drag & Drop, Smart-Move & Animationen
```

View File

Some files were not shown because too many files have changed in this diff Show More