commit 163a3665d2a5a8afb73dd4643fa870d1143916ac Author: thw Date: Sat Nov 14 05:25:51 2026 +0100 first commit diff --git a/README.md b/README.md new file mode 100644 index 0000000..ec4bf89 --- /dev/null +++ b/README.md @@ -0,0 +1,179 @@ +# † The Goth Cardgame Collection † + +**[Deutsch](#deutsch) | [English](#english)** + +--- + + +## 🇩🇪 Deutsch + +### Überblick +**The Goth Cardgame Collection** ist eine erweiterbare Desktop-Kartenspielsammlung in Python (`tkinter` + `Pillow` + `SQLite`) im düsteren Gothic-Tarot-Stil. Das Projekt trennt strikt zwischen reinen Account-Profilen („Seelen“), spielgebundenem Fortschritt und einer zweigeteilten Datenbank-Architektur für unveränderliche Stammdaten und dynamische Spielstände. + +### Kern-Features des Hauptprogramms + +* **Seelen-Profile & Spielgebundene Progression:** + * Ein Profil speichert lediglich die Identität des Spielers („Seele“). + * **Kein Cross-Game-Grinding:** Jedes Spiel besitzt ein komplett eigenes Level, eigene Erfahrungspunkte (XP) und eigene Konsequenzen. Wer in Solitaire aufsteigt, kann diese XP nicht für Casino-Gold in Blackjack oder Poker zweckentfremden. + * **1.295+ Prestige-Stufen:** 259 Ränge mit je 5 römischen Unterstufen (`Erst-Starter I` bis `Schöpfergeist V`), gefolgt vom offenen Endlos-Rang **`Gottheit 1, 2, 3...`** (ab Level 1.296). +* **Flache 4-Kategorien-Architektur (ohne Untermenüs):** + * **Glück (`luck`):** Casino- und Wettspiele (*Blackjack*, *Texas Hold'em*) mit harten Konsequenzen, Goldbeuteln, *Divine Punishment* und *The Devil's Deal*. + * **Solo (`solo`):** Reine Logik- und Geduldsspiele (*Klondike*, *FreeCell*, *Spider Solitaire*) ohne Gold-Zwang und mit eigenen Rückstufungsregeln. + * **Gesellschaft - Offline (`party_offline`):** Klassische Runden am lokalen Tisch gegen KI-Charaktere. + * **Online (`online`):** Kein Welpenschutz – Partien gegen echte Gegner sowie entfesselte KI-Spieler auf **Gottheit-Niveau (Stufe 6)**. +* **Dynamischer Game-Loader (Plugin-Prinzip):** + * Neue Spiele werden einfach als Ordner mit einer `start.py` unter `games/` abgelegt und in `GAME_FOLDERS` registriert (`start_game(context)`, `GAME_TITLE_KEY`, `GAME_CATEGORY`). +* **Duale SQLite-Datenbank-Architektur:** + * `resources/code_res/internal_base.db` *(Read-Only Stammdaten)*: Enthält alle Übersetzungen (`base_i18n`), alle 260 Prestige-Ränge (`base_prestige_ranks`) und Spielvarianten (`game_variants`). Wird per `ATTACH DATABASE ... AS core` eingebunden. + * `user_data.db` *(Dynamische Nutzerdaten)*: Speichert Profile, spielgebundene XP & Level-Historien, Goldbeutel, Bot-Setups, Fenstergeometrie, Audio-Settings, Statistiken und Pakt-Savegames. +* **Dynamisches UI-System & Visuelles State-Feedback:** + * Eigene rahmenlose Alpha-PNG-Buttons (`ImageButton`) mit automatischem PIL-Graustufen- und Abdunklungsfilter (`enabled=False`) für inaktive Aktionen, gesperrte Tische oder fehlende Voraussetzungen. + * Vektorbasierte Gothic-Tarot-Spielkarten im Auswahlmenü sowie eine erweiterbare Topbar (`AppContext.build_game_topbar`) mit optionaler Direkteinbindung spielspezifischer Statistik-Ansichten und Live-Währungsanzeigen. +* **Live-Zweisprachigkeit (DE / EN):** + * Umschaltung zu jeder Zeit (im Hauptmenü, in Statistiken oder mitten im laufenden Spielzug) ohne Neustart. +* **Audio- & Atmosphären-Manager:** + * Getrennte Lautstärkeregler für Hintergrundmusik (*Beyond the Iron Gate* im Menü, *The Midnight Hand* am Spieltisch) und Soundeffekte, persistent in der DB gespeichert. +* **Detailliertes Statistik-Board:** + * Spiel- und variantenspezifische Auswertung für gespielte/gewonnene/verlorene Runden, Siegquote in %, aktuelle & längste Siegesserie sowie beste und durchschnittliche Spielzeit. + +### Verzeichnisstruktur + +```text +the_goth_cardgame_collection/ +├── main.py # Einstiegspunkt +├── README.md # Hauptdokumentation (DE/EN) +├── user_data.db # Dynamische Spieler- & Savegame-DB (wird automatisch erzeugt) +├── controller/ +│ ├── app_controller.py # Hauptsteuerung, Login, Kategorien & Devil's-Lock-Prüfung +│ ├── app_context.py # Schnittstelle & Topbar-Builder zwischen Hauptprogramm und Spiel +│ └── game_loader.py # Dynamischer Loader für Spiele unter games/ +├── models/ +│ ├── card.py # Karten-Modell +│ ├── deck.py # Deck-Verwaltung & Mischen +│ ├── database.py # Kapselung aller SQLite-Zugriffe & Transaktionen +│ ├── progression.py # Level-, XP- & Prestige-Berechnung (spielgebunden) +│ └── sound_manager.py # Musik- & SFX-Steuerung +├── resources/ +│ ├── code_res/ +│ │ ├── game_constants.py # Zentrale Konstanten, Kategorien, Farben & Balancing-Werte +│ │ ├── i18n.py # Übersetzungs-Cache & Formatierung +│ │ ├── sql_queries.py # Alle SQL-Statements zentral ausgelagert +│ │ ├── internal_base.sql # Vollständiger SQL-Dump der Stammdaten +│ │ └── internal_base.db # Kompilierte SQLite-Stammdatenbank +│ ├── images/ # UI-Grafiken & Kartendecks +│ └── sounds/ # Musik & Soundeffekte +├── view/ +│ ├── main_window.py # Hauptfenster, Geometrie-Speicherung & globale Styles +│ ├── assets_manager.py # Bild- & GIF-Caching +│ ├── dialogs/ # Modale Dialoge (z.B. Audio-Einstellungen) +│ ├── menus/ # LoginView, MainMenuView, StatisticsView +│ └── widgets/ # Wiederverwendbare UI-Bausteine (ImageButton inkl. Graufilter, StatsBoard, BotSetup) +└── games/ + └── blackjack/ # Blackjack – Devil's Gambit Modul (inkl. eigener README & StatsView) +``` + +### Installation & Start + +1. **Abhängigkeiten installieren:** + ```bash + pip install pillow pygame + ``` +2. **Stammdatenbank (`internal_base.db`) aus SQL-Dump erzeugen/aktualisieren:** + ```powershell + sqlite3 resources/code_res/internal_base.db ".read resources/code_res/internal_base.sql" + ``` +3. **Spiel starten:** + ```bash + python main.py + ``` + +### Spiele-Dokumentationen +* [Blackjack – Devil's Gambit (`games/blackjack/README.md`)](games/blackjack/README.md) + +--- + + +## 🇬🇧 English + +### Overview +**The Goth Cardgame Collection** is an extensible desktop card game suite built with Python (`tkinter` + `Pillow` + `SQLite`), styled in a dark Gothic Tarot aesthetic. The architecture strictly separates player identity ("Souls"), game-bound progression, and a dual-database setup for immutable core data versus dynamic player states. + +### Core Engine Features + +* **Soul Profiles & Game-Bound Progression:** + * A profile strictly represents the player's identity ("Soul"). + * **Zero Cross-Game Grinding:** Every game tracks its own independent XP, level, and consequences. Progress earned in Solitaire cannot be converted into casino gold for Blackjack or Poker. + * **1,295+ Prestige Levels:** 259 rank titles divided into 5 Roman sub-tiers (`First-Starter I` up to `Creator Spirit V`), followed by open-ended **`Deity 1, 2, 3...`** ranks starting at Level 1,296. +* **Flat 4-Category Structure (No Submenus):** + * **Luck (`luck`):** High-stakes gambling games (*Blackjack*, *Texas Hold'em*) featuring gold pouches, *Divine Punishment*, and *The Devil's Deal*. + * **Solo (`solo`):** Pure skill and patience games (*Klondike*, *FreeCell*, *Spider Solitaire*) with dedicated progression and demotion mechanics, free of gold entry fees. + * **Party - Offline (`party_offline`):** Classic parlor card games played locally against AI personalities. + * **Online (`online`):** No hand-holding – matches against human players and unleashed **Deity-tier bots (Level 6)**. +* **Dynamic Game Loader:** + * Games live in modular folders under `games/` exposing a `start.py` (`start_game(context)`, `GAME_TITLE_KEY`, `GAME_CATEGORY`). +* **Dual SQLite Database Architecture:** + * `resources/code_res/internal_base.db` *(Read-Only Core Data)*: Stores all translations (`base_i18n`), all 260 prestige titles (`base_prestige_ranks`), and game variants (`game_variants`), attached at runtime as `core`. + * `user_data.db` *(Dynamic User Data)*: Stores profiles, per-game XP & level history, gold pouches, bot setups, window geometry, audio preferences, statistics, and lock-state savegames. +* **Adaptive UI & Visual State Feedback:** + * Custom borderless alpha-PNG buttons (`ImageButton`) with automatic PIL grayscale/dimming filters (`enabled=False`) to clearly signal inactive actions, locked tables, or missing prerequisites. + * Vector-styled Gothic Tarot game cards in the main menu and an extensible topbar (`AppContext.build_game_topbar`) supporting dedicated per-game statistics views and live balance badges. +* **Instant Localization (DE / EN):** + * Toggle between German and English on the fly—even mid-hand—without restarting. +* **Audio & Ambiance System:** + * Separate volume controls for background music and menu/table sound effects, saved persistently. +* **Comprehensive Statistics Board:** + * Filterable per game and variant: games played/won/lost, win percentage, current & longest streak, best time, and average duration. + +### Directory Structure + +```text +the_goth_cardgame_collection/ +├── main.py # Entry point +├── README.md # Main documentation (DE/EN) +├── user_data.db # Dynamic player & savegame DB (auto-created) +├── controller/ +│ ├── app_controller.py # Core routing, login, categories & Devil's Lock check +│ ├── app_context.py # Bridge & topbar builder between host app and active game +│ └── game_loader.py # Dynamic discovery for modules inside games/ +├── models/ +│ ├── card.py # Playing card model +│ ├── deck.py # Shoe & shuffling logic +│ ├── database.py # SQLite abstraction & transaction handling +│ ├── progression.py # Game-bound XP, level & prestige calculation +│ └── sound_manager.py # Music & SFX controller +├── resources/ +│ ├── code_res/ +│ │ ├── game_constants.py # Central constants, categories, colors & balancing values +│ │ ├── i18n.py # Localization cache & string formatting +│ │ ├── sql_queries.py # Centralized SQL statements +│ │ ├── internal_base.sql # Complete SQL seed dump for static data +│ │ └── internal_base.db # Compiled read-only SQLite core database +│ ├── images/ # UI assets & card decks +│ └── sounds/ # Music tracks & sound effects +├── view/ +│ ├── main_window.py # Root window, geometry persistence & global ttk styles +│ ├── assets_manager.py # Image & animated GIF cache +│ ├── dialogs/ # Modal dialogs (e.g., Audio settings) +│ ├── menus/ # LoginView, MainMenuView, StatisticsView +│ └── widgets/ # Reusable UI widgets (ImageButton w/ gray filter, StatsBoard, BotSetup) +└── games/ + └── blackjack/ # Blackjack – Devil's Gambit module (incl. README & StatsView) +``` + +### Setup & Launch + +1. **Install dependencies:** + ```bash + pip install pillow pygame + ``` +2. **Build or update `internal_base.db` from the SQL seed:** + ```powershell + sqlite3 resources/code_res/internal_base.db ".read resources/code_res/internal_base.sql" + ``` +3. **Run the application:** + ```bash + python main.py + ``` + +### Game Manuals +* [Blackjack – Devil's Gambit (`games/blackjack/README.md`)](games/blackjack/README.md) \ No newline at end of file diff --git a/controller/__pycache__/app_context.cpython-311.pyc b/controller/__pycache__/app_context.cpython-311.pyc new file mode 100644 index 0000000..6c8885d Binary files /dev/null and b/controller/__pycache__/app_context.cpython-311.pyc differ diff --git a/controller/__pycache__/app_controller.cpython-311.pyc b/controller/__pycache__/app_controller.cpython-311.pyc new file mode 100644 index 0000000..b9dc18e Binary files /dev/null and b/controller/__pycache__/app_controller.cpython-311.pyc differ diff --git a/controller/__pycache__/game_loader.cpython-311.pyc b/controller/__pycache__/game_loader.cpython-311.pyc new file mode 100644 index 0000000..e1a6b54 Binary files /dev/null and b/controller/__pycache__/game_loader.cpython-311.pyc differ diff --git a/controller/app_context.py b/controller/app_context.py new file mode 100644 index 0000000..c8e87db --- /dev/null +++ b/controller/app_context.py @@ -0,0 +1,129 @@ +# -*- coding: utf-8 -*- +# controller/app_context.py +import tkinter as tk +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 resources.code_res.i18n import t +from view.dialogs.audio_settings_dialog import AudioSettingsDialog +from view.widgets.image_button import ImageButton + + +class AppContext: + def __init__(self, controller, game_folder: str): + self._ctrl = controller + self.game_folder = game_folder + self.root = controller.view + self.assets = controller.view.assets + self.sounds = controller.sounds + + @property + def profile(self) -> dict: + return self._ctrl.active_profile + + @property + def game_progress(self) -> dict: + return Database.get_game_progress(self.profile["id"], self.game_folder) + + def refresh_game_progress(self) -> dict: + return Database.get_game_progress(self.profile["id"], self.game_folder) + + def back_to_main_menu(self): + self._ctrl.show_main_menu() + + def open_audio_settings(self): + AudioSettingsDialog.open(self.root, self.assets, self.sounds) + + def toggle_language(self, refresh_callback=None): + self._ctrl.toggle_language(refresh_callback) + + def record_result( + self, + variant_key: str, + won: bool, + duration_sec: float, + points_gained: int = 0, + bj_account_id: int | None = None + ) -> tuple[int, int]: + if not self._ctrl.active_profile: + return (1, 1) + pid = self._ctrl.active_profile["id"] + old_lvl, new_lvl = Database.record_game_result( + pid, variant_key, won, duration_sec, points_gained, bj_account_id=bj_account_id + ) + self.sounds.play("end_battle" if new_lvl > old_lvl else ("win" if won else "lose")) + return old_lvl, new_lvl + + def build_game_topbar( + self, + parent, + title: str, + on_game_menu=None, + on_stats=None, + stats_enabled: bool = True, + extra_right_text: str = "", + on_lang_refresh=None, + locked_exit: bool = False, + ) -> tk.Frame: + bar = tk.Frame(parent, bg=PANEL_BG, padx=12, pady=8, highlightthickness=1, highlightbackground=SUBTLE_BORDER) + bar.pack(fill="x", side="top") + + stats_btn = None + if locked_exit: + tk.Label( + bar, text=t("devils_deal_locked_badge"), + font=("Helvetica", 10, "bold"), fg=ERROR_FG, bg=PANEL_BG + ).pack(side="left", padx=(4, 12)) + else: + ImageButton( + bar, t("btn_back_main"), self.assets.raw_sel, self.assets.raw_sel_active, + self.back_to_main_menu, sound_mgr=self.sounds, width=135, height=36, font=("Helvetica", 10, "bold") + ).pack(side="left", padx=(0, 6)) + + 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)) + + 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 \ No newline at end of file diff --git a/controller/app_controller.py b/controller/app_controller.py new file mode 100644 index 0000000..4511b94 --- /dev/null +++ b/controller/app_controller.py @@ -0,0 +1,106 @@ +# -*- coding: utf-8 -*- +# controller/app_controller.py +from pathlib import Path +from controller.app_context import AppContext +from controller.game_loader import GameLoader +from models.database import Database +from models.sound_manager import SoundManager +import resources.code_res.i18n as i18n +from resources.code_res.i18n import t + + +class AppController: + def __init__(self, root_dir: Path): + self.root_dir = root_dir + Database.init_db() + i18n.reload_translations() + i18n.set_lang(Database.load_setting("language", "DE")) + self.loader = GameLoader(root_dir) + self.sounds = SoundManager(root_dir / "resources" / "sounds") + self.active_profile = None + self.view = None + + def bind_view(self, view): + self.view = view + + def toggle_language(self, custom_refresh=None): + new_lang = i18n.next_lang() + Database.save_setting("language", new_lang) + self.view.title(t("app_title")) + if custom_refresh is not None: + custom_refresh() + elif self.active_profile: + self.show_main_menu() + else: + self.start() + + def start(self): + self.sounds.play_menu_music() + profiles = Database.get_profiles() + last_prof = Database.load_setting("last_profile_name", "") + self.view.show_login(profiles, preselect_name=last_prof) + + def do_login(self, name: str): + if not name: + return + Database.save_setting("last_profile_name", name) + self.active_profile = Database.get_or_create_profile(name) + self.show_main_menu() + + def do_create_profile(self, name: str): + if not name: + return + Database.save_setting("last_profile_name", name) + self.active_profile = Database.get_or_create_profile(name) + self.show_main_menu() + + def logout_to_login(self): + self.sounds.play_menu_music() + last_prof = self.active_profile["name"] if self.active_profile else Database.load_setting("last_profile_name", "") + self.active_profile = None + self.view.show_login(Database.get_profiles(), preselect_name=last_prof) + + def has_active_devils_lock(self) -> bool: + """Nur aktiv, wenn wirklich das DB-Flag devils_deal_active == 1 gesetzt wurde!""" + if not self.active_profile: + return False + pid = self.active_profile["id"] + devils_acc = Database.get_active_devils_bj_account(pid) + if devils_acc is None: + # Verwaiste Blackjack-Savegames ohne aktives Pakt-Flag sofort wegräumen + Database.delete_game_state(pid, "blackjack") + return False + return True + + def resume_devils_deal(self): + games = self.loader.discover_games() + for g in games: + if g["folder"] == "blackjack": + self.launch_game(g) + return + + def show_main_menu(self): + self.sounds.play_menu_music() + if self.active_profile: + pid = self.active_profile["id"] + self.active_profile = Database.get_profile_by_id(pid) + if self.has_active_devils_lock(): + self.view.show_main_menu(self.active_profile, [], devils_resume_only=True) + else: + games = self.loader.discover_games() + for g in games: + g["progress"] = Database.get_game_progress(pid, g["folder"]) + self.view.show_main_menu(self.active_profile, games, devils_resume_only=False) + + def show_statistics(self): + if self.has_active_devils_lock(): + return + self.sounds.play_menu_music() + if self.active_profile: + self.active_profile = Database.get_profile_by_id(self.active_profile["id"]) + self.view.show_statistics(self.active_profile) + + def launch_game(self, game_entry: dict): + self.view.clear_window(apply_global_bg=True) + ctx = AppContext(self, game_folder=game_entry["folder"]) + game_entry["start"](ctx) \ No newline at end of file diff --git a/controller/game_loader.py b/controller/game_loader.py new file mode 100644 index 0000000..842c4c0 --- /dev/null +++ b/controller/game_loader.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# controller/game_loader.py +import importlib.util +import sys +from pathlib import Path + +from resources.code_res.game_constants import ( + CAT_LUCK, ENTRY_FILENAME, FOLDER_CATEGORY_MAP, GAME_FOLDERS, GAMES_ROOT_DIR +) +from resources.code_res.i18n import t + + +class GameLoader: + def __init__(self, root_dir: Path): + self.games_dir = root_dir / GAMES_ROOT_DIR + + def discover_games(self) -> list[dict]: + discovered = [] + for rel_folder in GAME_FOLDERS: + entry_file = self.games_dir / rel_folder / ENTRY_FILENAME + if not entry_file.is_file(): + continue + + mod_name = "goth_game_" + rel_folder.replace("/", "_") + spec = importlib.util.spec_from_file_location(mod_name, entry_file) + if spec and spec.loader: + module = importlib.util.module_from_spec(spec) + sys.modules[mod_name] = module + spec.loader.exec_module(module) + + if hasattr(module, "start_game"): + title_key = getattr(module, "GAME_TITLE_KEY", None) + title = ( + t(title_key) + if title_key + else getattr(module, "GAME_TITLE", rel_folder.split("/")[-1].replace("_", " ").title()) + ) + category = getattr( + module, + "GAME_CATEGORY", + FOLDER_CATEGORY_MAP.get(rel_folder, CAT_LUCK), + ) + discovered.append({ + "folder": rel_folder, + "category": category, + "title": title, + "start": module.start_game, + }) + return discovered \ No newline at end of file diff --git a/games/__init__.py b/games/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/games/__pycache__/__init__.cpython-311.pyc b/games/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..7edd154 Binary files /dev/null and b/games/__pycache__/__init__.cpython-311.pyc differ diff --git a/games/blackjack/README.md b/games/blackjack/README.md new file mode 100644 index 0000000..3ebec48 --- /dev/null +++ b/games/blackjack/README.md @@ -0,0 +1,214 @@ +# † Blackjack – Devil's Gambit † + +**[Deutsch](#deutsch) | [English](#english)** + +--- + + +## 🇩🇪 Deutsch + +### Überblick +**Blackjack – Devil's Gambit** kombiniert klassische Vegas-Kartenregeln mit einem gnadenlosen Multi-Player-Goldpot, spiellevel-skalierten Erhöhungen, **Divine Punishment** auf Gottheit-Rang und dem unausweichlichen **Devil's Deal**. + +### 1. Kontoverwaltung, UI-Logik & Grundregeln + +* **Bewusstes Goldbeutel-System (0–5 Konten):** + * Neue Seelen starten ohne automatisch aufgezwungenes Startkonto. Erst nach dem bewussten Anlegen eines Goldbeutels (bis zu **5 separate Konten**, Startkapital je **1.000 Gold**) werden Gegner-Setup, XP-Umtausch, Tischauswahl und Konto-Statistiken freigeschaltet. + * Nicht klickbare Elemente (fehlendes Konto, zu wenig Gold für den Tisch oder nicht genügend XP für den Tausch) werden visuell über einen **automatischen Graustufen-Filter** gesperrt. +* **Permanente Gold-Transparenz & Eigene Statistik-Ansicht:** + * Sobald ein Goldbeutel ausgewählt ist, wird das aktuelle Guthaben dauerhaft **sowohl oben rechts in der Topbar als auch prominent im Gold-Banner** des Kontomenüs angezeigt. + * Über den eigenen Button **`Statistiken`** in der Topbar öffnet sich `BlackjackStatsView` als dedizierte Ansicht zur Auswertung jedes einzelnen Goldbeutels (inkl. Tischfilter). +* **Fester Grundeinsatz (Ante):** Zu Beginn jeder Runde legt jeder Teilnehmer (Spieler & aktive Bots) exakt **10 Gold** Grundeinsatz in den gemeinsamen Pot. +* **Kartenverteilung:** + * Du erhältst 2 eigene Karten (für dich sichtbar, für Gegner verdeckt). + * Bis zu 3 KI-Gegner erhalten jeweils 2 verdeckte Karten. + * Der **Haus-Dealer** erhält 1 offene Karte (*Upcard*) und 1 verdeckte Karte (*Hole Card*). +* **Dealer-Regel:** Der Haus-Dealer muss bei **16 oder weniger** weitere Karten ziehen (*Hit*) und bleibt ab **17 bis 21** stehen (*Stand*). +* **No Surrender:** Ein vorzeitiges Aufgeben gegen halben Einsatz existiert nicht. Wer aussteigt, lässt sein gesamtes bisher gesetztes Gold im Pot zurück. +* **Sofortsieg `7-7-7`:** Hält ein Spieler oder Bot drei Siebenen (`7-7-7`), endet die Runde augenblicklich und der gesamte Pot geht sofort an diese Hand. +* **Tischvarianten:** + * **Klassisch (`bj_classic`):** 2 Decks, einfacher Level-Einsatzmultiplikator (`1x`), `1.0x` XP. + * **Hoher Einsatz (`bj_highstakes`):** 6 Decks, doppelter Level-Einsatzmultiplikator (`2x`), `1.45x` XP. + +### 2. Devil's Gambit: Der 4-Stufen-Ablaufbaum + +Jeder Zug eines Spielers (und jedes Bots) durchläuft strikt nacheinander vier Entscheidungsknoten. Erhöhungen erscheinen erst, nachdem man sich aktiv fürs Weiterspielen entschieden hat: + +```text ++------------------+ +| Rundenstart | (10 Gold Grundeinsatz pro Person -> je 2 Karten) ++---------+--------+ + | ++---------v--------+ +----------------------------+ +| 1. Mitgehen? +--- Nein (eben) ----> Als FERTIG markiert | ++---------+--------+ +-------------+--------------+ + | | + +--- Nein (gegen Erhöhung) ---> VERLOREN! | + | (Gold im Pot verloren) | | + Ja | | + | | | ++---------v--------+ | | +| 2. Ziehen? +-- Nein --+ | | +| (Hit/Double/Split| | | | ++---------+--------+ | | | + Ja | | | + | | | | ++---------v--------+ | v v +| Karte gezogen! | | +------------------+ +| Über 21? +-- Ja ----+---------> Nächster Spieler | ++---------+--------+ | | (Verloren / Out) | + Nein | +------------------+ + | | ++---------v-------------------v-+ +------------------+ +| 3. Erhöhen? +--Ja---> Pot erhöhen! | +| (Chips skalieren mit Level) | | (Zwingt Gegner | ++---------+---------------------+ | zum Mitgehen) | + Nein +--------+---------+ + | | ++---------v--------+ | +| 4. Fertig? +-- Ja (Karten sperren) ------+ ++---------+--------+ | + Nein (Offen bleiben) | + | | ++---------v--------------------------------------v-+ +| Nächster Spieler am Zug | ++--------------------------------------------------+ +``` + +#### Besondere Karten-Aktionen in Schritt 2 (`Ziehen?`) +* **Hit (Karte ziehen):** Zieht 1 Karte. Unter/gleich 21 geht es weiter zu Schritt 3 (*Erhöhen?*), über 21 ist die Hand sofort raus (*Bust*). +* **Double Down (Verdoppeln):** Nur bei genau 2 Startkarten möglich. Verdoppelt deinen Einsatz auf das Doppelte des aktuellen Tisch-Höchsteinsatzes, zieht **genau eine** Karte und sperrt die Hand automatisch als *Fertig*. +* **Split (Teilen):** Haben deine ersten beiden Karten denselben Blackjack-Wert, kannst du gegen einen zweiten Einsatz zwei getrennte Hände parallel weiterspielen. +* **Level-skalierte Erhöhungen:** Während der Grundeinsatz beim Geben immer bei 10 Gold bleibt, wachsen deine vier Erhöhungs-Chips in Schritt 3 automatisch alle 5 Blackjack-Level (mit jedem neuen Prestige-Rang) mit. Pro Runde sind bis zu 4 Erhöhungen möglich. + +### 3. KI-Gegner (Stufe 0 bis Gottheit) + +Du kannst bis zu **3 Bots** gleichzeitig an den Tisch setzen: +* **Stufe 0 – Verwirrte Seele:** Unberechenbare Zufallszüge. +* **Stufe 1 – Akolyth:** Vorsichtiges Spiel, hält früh. +* **Stufe 2 – Nachtwanderer:** Solide Grundwerte, jagt bei zwei 7ern aktiv die `7-7-7`. +* **Stufe 3 – Schatten-Zocker:** Bezieht die offene Karte des Haus-Dealers ein. +* **Stufe 4 – Experte:** Spielt mathematische Basisstrategie (Dealer Stands on 17). +* **Stufe 5 – Großmeister:** Zählt alle offenen Karten per Hi-Lo-System (*Running & True Count*) über den gesamten Kartenschuh mit. +* **Stufe 6 – Gottheit (Gnadenlos / Online-Standard):** Nutzt vollständige *Illustrious-18*-Indexabweichungen, erhöht bei positivem True Count kompromisslos mit Maximal-Chips, nutzt aggressives Double-Down-Timing und steigt bei negativer Erwartung gegen teure Raises eiskalt aus. + +### 4. Gold-Umtausch, Divine Punishment & The Devil's Deal + +Sinkt ein Goldbeutel unter das Tischminimum von **10 Gold**, greift ein mehrstufiges System, das ausschließlich an dein **Blackjack-Level** gekoppelt ist: + +1. **Regulärer Umtausch (bis einschl. `Schöpfergeist V`, bevor jemals `Gottheit` erreicht wurde):** + * Fester Kurs: **10.000 Blackjack-XP → +10 Gold**. +2. **Divine Punishment Mode (ab erstmaligem Erreichen von `Gottheit 1` / Level 1.296):** + * Ab sofort wird für jedes Level ab `Schöpfergeist V` dein realer XP-Durchschnitt pro Partie aufgezeichnet. + * **Strafkurs:** +10 Gold kosten das **10-Fache deines durchschnittlichen XP-Gewinns aus dem vorherigen Level** (z. B. Ø 34 Mio. XP auf `Schöpfergeist V` → **340 Mio. XP** für +10 Gold). + * **Harter Boden (Floor):** Du kannst durch *Divine Punishment* niemals auf Level 0 abstürzen, sondern fällst **maximal bis auf die exakte Unterkante von `Schöpfergeist V`** zurück. +3. **The Devil's Deal (Am Abgrund von `Schöpfergeist V`):** + * Stehst du ohne verbleibenden XP-Puffer auf der Untergrenze von `Schöpfergeist V`, sperrt sich der XP-Tausch und **The Devil's Deal** öffnet sich. + * **Seelen-Opfer:** Du kannst ein **anderes Seelen-Profil** aus der Datenbank opfern (unwiderruflich löschen!), sofern dieses andere Profil **in Blackjack mindestens Rang `Stütze I` (Level 421+)** erreicht hat. Dafür erhältst du **+10 Teufelsmünzen**. + * **Unausweichlicher Lock & Auto-Save:** Sobald die 10 Teufelsmünzen angenommen wurden, startet das Spiel sofort am gesperrten Tisch (`devils_deal_active = 1`). Alle Zurück-Buttons und anderen Spiele im Hauptmenü verschwinden. Nach **jedem einzelnen Klick** speichert das Spiel den kompletten Tischzustand in der Datenbank. Schließt du das Fenster, existiert beim nächsten Login ausschließlich **„Pakt fortsetzen (Resume)“**, bis der Pakt durch Sieg oder Bankrott entschieden ist! + +### Modulstruktur (`games/blackjack/`) + +```text +games/blackjack/ +├── start.py # Einstiegspunkt & Devil's-Deal-Lock-Routing +├── README.md # Spielspezifische Dokumentation (DE/EN) +├── models/ +│ ├── blackjack_engine.py # Spiel-Logik, Deck, Pot, Split/Double & JSON-Serialisierung +│ ├── hand_evaluator.py # Punktberechnung, Soft-Hands, Blackjack & 7-7-7 Prüfung +│ ├── player_hand.py # Datenmodell für Spielerhände (inkl. Split-Status) +│ ├── bot_seat.py # Sitz- & Statusmodell für KI-Gegner +│ └── bot_ai.py # 4-Stufen-KI von Stufe 0 bis Stufe 6 (Gottheit / Hi-Lo Counter) +└── views/ + ├── blackjack_menu_view.py # Kontoverwaltung, Gold-Banner, Gegner-Setup & Tischwahl + ├── blackjack_stats_view.py # Dedizierte Konto-Statistik-Ansicht pro Goldbeutel + ├── blackjack_table_view.py # Spieltisch, 4-Knoten-Ablaufbaum & Auto-Save-Persistenz + └── round_result_dialog.py # Runden-Auswertung mit Gewinn/Verlust-GIFs & Level-Up-Anzeige +``` + +--- + + +## 🇬🇧 English + +### Overview +**Blackjack – Devil's Gambit** fuses classic Vegas card rules with a ruthless multi-player gold pot, level-scaled bet raises, **Divine Punishment** at Deity rank, and the inescapable **Devil's Deal**. + +### 1. Account Management, UI Logic & Core Rules + +* **Deliberate Gold Pouch System (0–5 Accounts):** + * New Souls start cleanly with zero pre-created accounts. Only after explicitly creating a Gold Pouch (up to **5 independent pouches**, **1,000 Gold** starting balance each) do opponent setup, XP exchange, table entry, and account statistics unlock. + * Unavailable actions (no account created yet, insufficient gold for table entry, or insufficient XP for exchange) are visually locked using an **automatic grayscale dimming filter**. +* **Persistent Gold Visibility & Dedicated Stats View:** + * Once a pouch is active, your current Gold balance is permanently displayed **both in the topbar and inside a prominent Gold banner** within the account panel. + * Clicking **`Statistics`** in the topbar opens `BlackjackStatsView`, a dedicated full-screen statistics breakdown for each individual Gold Pouch (filterable by table variant). +* **Fixed Initial Ante:** Every participant (player & active bots) places a mandatory **10 Gold** entry ante into the shared pot when cards are dealt. +* **Dealing & Visibility:** + * You receive 2 cards (visible to you, hidden from opponents). + * Up to 3 AI opponents receive 2 hidden cards each. + * The **House Dealer** receives 1 face-up card (*Upcard*) and 1 face-down card (*Hole Card*). +* **Dealer Rule:** The House Dealer hits on **16 or less** and stands on **17 through 21**. +* **No Surrender:** Leaving a hand forfeits every coin you have already committed to the pot. +* **Instant `7-7-7` Victory:** Holding three Sevens (`7-7-7`) immediately ends the round and awards the entire pot to that hand. +* **Variants:** + * **Classic (`bj_classic`):** 2 decks, `1x` level chip scale, `1.0x` XP multiplier. + * **High Stakes (`bj_highstakes`):** 6 decks, `2x` level chip scale, `1.45x` XP multiplier. + +### 2. Devil's Gambit: 4-Step Turn Flowchart + +Every turn follows a strict 4-step decision tree. Raising options only unlock after committing to stay in the hand: + +1. **Step 1 – Match Bet / Continue?** + * If an opponent raised, you must match the deficit (`+{X} Gold`) to stay alive—declining eliminates your hand immediately (*Lost*). + * If no raise is pending, choose **Continue Playing** to enter your turn, or **Mark as Ready** to lock your cards right away and pass to the next seat. +2. **Step 2 – Draw Card?** *(Skipped if your cards are already locked)* + * Choose **Draw Card (Hit)**, **Double Down** (on 2 cards: doubles table bet, draws 1 card, locks hand), **Split** (on equal-value pair: places second bet to play two hands side-by-side), or **No Card**. + * Exceeding 21 results in an immediate **Bust** and passes the turn. +3. **Step 3 – Raise Bet?** + * Pick one of your 4 **level-scaled raise chips** (scaling up every 5 Blackjack levels) to increase the table stake and force all other active players—even those who already locked their cards—to match on their next turn, or choose **No Raise**. +4. **Step 4 – Ready?** + * Choose **Yes — Ready (Lock Cards)** so you draw no further cards, or **No — Next Player** to keep your hand open for the next cycle. + +### 3. AI Personalities (Level 0 to Deity) + +* **Level 0 – Lost Soul:** Unpredictable random decisions. +* **Level 1 – Acolyte:** Cautious play, stands early. +* **Level 2 – Nightwalker:** Solid fundamentals, actively chases `7-7-7` on paired Sevens. +* **Level 3 – Shadow Gambler:** Evaluates the House Dealer's upcard. +* **Level 4 – Expert:** Executes optimal Dealer-Stands-on-17 Basic Strategy. +* **Level 5 – Grandmaster:** Tracks the shoe using Hi-Lo card counting (*Running & True Count*). +* **Level 6 – Deity (Merciless / Online Standard):** Full *Illustrious-18* count index deviations, maximum value-raising pressure on strong hands/counts, optimal soft & hard Double Downs, and disciplined folds against unfavorable pot odds. + +### 4. Gold Exchange, Divine Punishment & The Devil's Deal + +When a pouch drops below the **10 Gold** table minimum, progression rules bound strictly to your **Blackjack level** apply: + +1. **Standard Exchange (Before ever reaching `Deity 1`):** + * Fixed rate: **10,000 Blackjack XP → +10 Gold**. +2. **Divine Punishment Mode (Upon reaching `Deity 1` / Level 1,296+):** + * The game records your real average XP earned per match for every level starting at `Creator Spirit V`. + * **Punishment Rate:** +10 Gold costs **10x your average match XP from the previous level**. + * **Hard Floor:** Divine Punishment can never drop you to zero—your fall is strictly capped at the exact floor of **`Creator Spirit V`**. +3. **The Devil's Deal (At the floor of `Creator Spirit V`):** + * Once stranded at the bottom of `Creator Spirit V`, XP exchange locks and **The Devil's Deal** awakens. + * **Soul Sacrifice:** Permanently erase **another Soul profile** that has reached at least **`Support I` (Level 421+) in Blackjack** to receive **+10 Devil's Coins**. + * **No Escape & Per-Click Auto-Save:** Accepting the pact immediately locks you at the Blackjack table (`devils_deal_active = 1`). All exit buttons and other games are disabled, and every single button click auto-saves the entire table, shoe, and pot state to SQLite. Closing and reopening the app presents **Resume Pact** as your sole option until you either win your way free or lose the last coin! + +### Module Structure (`games/blackjack/`) + +```text +games/blackjack/ +├── start.py # Module entry point & Devil's Deal lock routing +├── README.md # Game-specific manual (DE/EN) +├── models/ +│ ├── blackjack_engine.py # Core rules, shoe, pot, Split/Double & JSON state serialization +│ ├── hand_evaluator.py # Hand scoring, soft totals, natural Blackjack & 7-7-7 detection +│ ├── player_hand.py # Data model for player hands (incl. split tracking) +│ ├── bot_seat.py # Seat & status model for AI opponents +│ └── bot_ai.py # 4-step flowchart AI from Level 0 up to Level 6 (Deity counter) +└── views/ + ├── blackjack_menu_view.py # Account management, Gold banner, bot setup & variant cards + ├── blackjack_stats_view.py # Dedicated per-pouch statistics screen + ├── blackjack_table_view.py # Game table UI, 4-node turn state machine & per-click auto-save + └── round_result_dialog.py # Showdown modal with win/loss GIFs & level-up banner +``` \ No newline at end of file diff --git a/games/blackjack/__pycache__/start.cpython-311.pyc b/games/blackjack/__pycache__/start.cpython-311.pyc new file mode 100644 index 0000000..29fb526 Binary files /dev/null and b/games/blackjack/__pycache__/start.cpython-311.pyc differ diff --git a/games/blackjack/models/__pycache__/blackjack_engine.cpython-311.pyc b/games/blackjack/models/__pycache__/blackjack_engine.cpython-311.pyc new file mode 100644 index 0000000..0d03dab Binary files /dev/null and b/games/blackjack/models/__pycache__/blackjack_engine.cpython-311.pyc differ diff --git a/games/blackjack/models/__pycache__/bot_ai.cpython-311.pyc b/games/blackjack/models/__pycache__/bot_ai.cpython-311.pyc new file mode 100644 index 0000000..23b958f Binary files /dev/null and b/games/blackjack/models/__pycache__/bot_ai.cpython-311.pyc differ diff --git a/games/blackjack/models/__pycache__/bot_seat.cpython-311.pyc b/games/blackjack/models/__pycache__/bot_seat.cpython-311.pyc new file mode 100644 index 0000000..fb6ca63 Binary files /dev/null and b/games/blackjack/models/__pycache__/bot_seat.cpython-311.pyc differ diff --git a/games/blackjack/models/__pycache__/hand_evaluator.cpython-311.pyc b/games/blackjack/models/__pycache__/hand_evaluator.cpython-311.pyc new file mode 100644 index 0000000..13c4347 Binary files /dev/null and b/games/blackjack/models/__pycache__/hand_evaluator.cpython-311.pyc differ diff --git a/games/blackjack/models/__pycache__/player_hand.cpython-311.pyc b/games/blackjack/models/__pycache__/player_hand.cpython-311.pyc new file mode 100644 index 0000000..620c29e Binary files /dev/null and b/games/blackjack/models/__pycache__/player_hand.cpython-311.pyc differ diff --git a/games/blackjack/models/blackjack_engine.py b/games/blackjack/models/blackjack_engine.py new file mode 100644 index 0000000..114d128 --- /dev/null +++ b/games/blackjack/models/blackjack_engine.py @@ -0,0 +1,457 @@ +# -*- coding: utf-8 -*- +# games/blackjack/models/blackjack_engine.py +from games.blackjack.models.bot_seat import BlackjackBotSeat +from games.blackjack.models.hand_evaluator import HandEvaluator +from games.blackjack.models.player_hand import PlayerHand +from models.card import Card +from models.deck import Deck +from resources.code_res.game_constants import BJ_DEALER_STAND, BJ_RESHUFFLE_RATIO, BJ_TARGET_SCORE + + +class BlackjackEngine: + def __init__(self, num_decks: int = 2): + self.num_decks = num_decks + self.deck = Deck(num_decks=num_decks, include_jokers=False) + + self.player_hands: list[PlayerHand] = [] + self.dealer_hand: list[Card] = [] + + self.pot: int = 0 + self.highest_bet: int = 0 + self.raises_in_round: int = 0 + self.state: str = "PRE_DEAL" + + @property + def total_player_bet(self) -> int: + return sum(h.bet_in_pot for h in self.player_hands) + + @property + def any_player_hand_active(self) -> bool: + return any(h.is_active_in_pot for h in self.player_hands) + + # --- JSON-Serialisierung für Devil's Deal Auto-Save --- + @staticmethod + def _cards_to_list(cards: list[Card]) -> list[list[str]]: + return [[c.suit, c.rank] for c in cards] + + @staticmethod + def _list_to_cards(raw: list[list[str]]) -> list[Card]: + return [Card(s, r) for s, r in raw] + + def to_dict(self, bots: list[BlackjackBotSeat]) -> dict: + return { + "num_decks": self.num_decks, + "deck_cards": self._cards_to_list(self.deck.cards), + "dealer_hand": self._cards_to_list(self.dealer_hand), + "pot": self.pot, + "highest_bet": self.highest_bet, + "raises_in_round": self.raises_in_round, + "state": self.state, + "player_hands": [ + { + "cards": self._cards_to_list(h.cards), + "bet_in_pot": h.bet_in_pot, + "cards_locked": h.cards_locked, + "busted": h.busted, + "folded": h.folded, + "doubled": h.doubled, + "is_split_hand": h.is_split_hand, + "acted_once": h.acted_once, + } + for h in self.player_hands + ], + "bots": [ + { + "name": b.name, + "ai_level": b.ai_level, + "gold": b.gold, + "hand": self._cards_to_list(b.hand), + "bet_in_pot": b.bet_in_pot, + "cards_locked": b.cards_locked, + "busted": b.busted, + "folded": b.folded, + "doubled": b.doubled, + "acted_once": b.acted_once, + "status_text": b.status_text, + "rebought": b.rebought, + } + for b in bots + ], + } + + def load_from_dict(self, data: dict) -> list[BlackjackBotSeat]: + self.num_decks = data["num_decks"] + self.deck.num_decks = self.num_decks + self.deck.cards = self._list_to_cards(data["deck_cards"]) + self.dealer_hand = self._list_to_cards(data["dealer_hand"]) + self.pot = data["pot"] + self.highest_bet = data["highest_bet"] + self.raises_in_round = data.get("raises_in_round", 0) + self.state = data["state"] + + self.player_hands = [ + PlayerHand( + cards=self._list_to_cards(hd["cards"]), + bet_in_pot=hd["bet_in_pot"], + cards_locked=hd["cards_locked"], + busted=hd["busted"], + folded=hd["folded"], + doubled=hd.get("doubled", False), + is_split_hand=hd.get("is_split_hand", False), + acted_once=hd.get("acted_once", False), + ) + for hd in data["player_hands"] + ] + + restored_bots = [] + for bd in data.get("bots", []): + restored_bots.append( + BlackjackBotSeat( + name=bd["name"], + ai_level=bd["ai_level"], + gold=bd["gold"], + hand=self._list_to_cards(bd["hand"]), + bet_in_pot=bd["bet_in_pot"], + cards_locked=bd.get("cards_locked", bd.get("ready", False)), + busted=bd["busted"], + folded=bd["folded"], + doubled=bd.get("doubled", False), + acted_once=bd.get("acted_once", False), + status_text=bd["status_text"], + rebought=bd["rebought"], + ) + ) + return restored_bots + + def check_reshuffle(self, min_needed: int = 28) -> bool: + threshold = max(min_needed, int(52 * self.num_decks * BJ_RESHUFFLE_RATIO)) + if self.deck.remaining() < threshold: + self.deck.reset(shuffle=True) + return True + return False + + def deal_initial_round(self, ante: int, player_avail_gold: int, bots: list[BlackjackBotSeat]) -> int: + ante = int(ante) + p_ante = min(ante, player_avail_gold) + + self.pot = p_ante + self.highest_bet = p_ante + self.raises_in_round = 0 + + p_cards = [self.deck.draw(), self.deck.draw()] + p_val, _ = HandEvaluator.evaluate(p_cards) + self.player_hands = [ + PlayerHand( + cards=p_cards, + bet_in_pot=p_ante, + cards_locked=(p_val == BJ_TARGET_SCORE), + acted_once=False, + ) + ] + self.dealer_hand = [self.deck.draw(), self.deck.draw()] + + for bot in bots: + b_ante = min(ante, bot.gold) + bot.gold -= b_ante + bot.bet_in_pot = b_ante + self.pot += b_ante + self.highest_bet = max(self.highest_bet, b_ante) + + b_cards = [self.deck.draw(), self.deck.draw()] + b_val, _ = HandEvaluator.evaluate(b_cards) + bot.hand = b_cards + bot.cards_locked = (b_val == BJ_TARGET_SCORE) + bot.busted = False + bot.folded = False + bot.doubled = False + bot.acted_once = False + bot.status_text = "" + + self.state = "ACTION_LOOP" + return p_ante + + # --- Karten- & Einsatz-Operationen (Spieler) --- + def can_split_hand(self, hand_idx: int, wallet_gold: int) -> bool: + if len(self.player_hands) != 1 or hand_idx != 0: + return False + h = self.player_hands[0] + if not h.is_active_in_pot or h.cards_locked or len(h.cards) != 2: + return False + if h.cards[0].blackjack_value != h.cards[1].blackjack_value: + return False + return wallet_gold >= self.highest_bet + + def split_player_hand(self) -> int: + """Teilt das Paar in 2 separate Hände auf und platziert den zweiten Einsatz in den Pot.""" + orig = self.player_hands[0] + second_bet = self.highest_bet + c1, c2 = orig.cards[0], orig.cards[1] + + h1_cards = [c1, self.deck.draw()] + h2_cards = [c2, self.deck.draw()] + v1, _ = HandEvaluator.evaluate(h1_cards) + v2, _ = HandEvaluator.evaluate(h2_cards) + + h1 = PlayerHand( + cards=h1_cards, + bet_in_pot=orig.bet_in_pot, + cards_locked=(v1 == BJ_TARGET_SCORE), + is_split_hand=True, + acted_once=False, + ) + h2 = PlayerHand( + cards=h2_cards, + bet_in_pot=second_bet, + cards_locked=(v2 == BJ_TARGET_SCORE), + is_split_hand=True, + acted_once=False, + ) + self.player_hands = [h1, h2] + self.pot += second_bet + return second_bet + + def get_double_down_cost(self, hand_idx: int) -> int: + h = self.player_hands[hand_idx] + target_bet = max(self.highest_bet, h.bet_in_pot) * 2 + return max(0, target_bet - h.bet_in_pot) + + def can_double_down(self, hand_idx: int, wallet_gold: int, already_drew_this_turn: bool) -> bool: + h = self.player_hands[hand_idx] + if not h.is_active_in_pot or h.cards_locked or already_drew_this_turn or len(h.cards) != 2: + return False + val, _ = HandEvaluator.evaluate(h.cards) + if val >= BJ_TARGET_SCORE: + return False + cost = self.get_double_down_cost(hand_idx) + return cost > 0 and wallet_gold >= cost + + def double_down_player_hand(self, hand_idx: int) -> tuple[int, Card]: + """Verdoppelt den Einsatz, zieht genau 1 Karte und sperrt die Hand.""" + cost = self.get_double_down_cost(hand_idx) + paid = self.player_add_gold_to_pot(hand_idx, cost) + h = self.player_hands[hand_idx] + card = self.player_draw_card(hand_idx) + h.doubled = True + h.cards_locked = True + h.acted_once = True + return paid, card + + def player_add_gold_to_pot(self, hand_idx: int, amount: int) -> int: + amt = max(0, int(amount)) + if amt == 0: + return 0 + h = self.player_hands[hand_idx] + h.bet_in_pot += amt + self.pot += amt + if h.bet_in_pot > self.highest_bet: + self.highest_bet = h.bet_in_pot + self.raises_in_round += 1 + return amt + + def player_draw_card(self, hand_idx: int) -> Card: + h = self.player_hands[hand_idx] + card = self.deck.draw() + h.cards.append(card) + val, _ = HandEvaluator.evaluate(h.cards) + if val > BJ_TARGET_SCORE: + h.busted = True + h.cards_locked = True + h.acted_once = True + elif val == BJ_TARGET_SCORE: + h.cards_locked = True + return card + + # --- Karten- & Einsatz-Operationen (Bots) --- + def bot_add_gold_to_pot(self, bot: BlackjackBotSeat, amount: int) -> int: + amt = max(0, min(int(amount), bot.gold)) + if amt == 0: + return 0 + bot.gold -= amt + bot.bet_in_pot += amt + self.pot += amt + if bot.bet_in_pot > self.highest_bet: + self.highest_bet = bot.bet_in_pot + self.raises_in_round += 1 + return amt + + def bot_draw_card(self, bot: BlackjackBotSeat) -> Card: + card = self.deck.draw() + bot.hand.append(card) + val, _ = HandEvaluator.evaluate(bot.hand) + if val > BJ_TARGET_SCORE: + bot.busted = True + bot.cards_locked = True + bot.acted_once = True + elif val == BJ_TARGET_SCORE: + bot.cards_locked = True + return card + + # --- Zug- & Abschluss-Prüfungen --- + def player_hand_needs_turn(self, hand: PlayerHand, wallet_gold: int) -> bool: + if not hand.is_active_in_pot: + return False + needs_call = (hand.bet_in_pot < self.highest_bet and wallet_gold > 0) + return (not hand.acted_once) or (not hand.cards_locked) or needs_call + + def bot_needs_turn(self, bot: BlackjackBotSeat) -> bool: + if not bot.is_active_in_pot: + return False + needs_call = (bot.bet_in_pot < self.highest_bet and bot.gold > 0) + return (not bot.acted_once) or (not bot.cards_locked) or needs_call + + def is_everyone_finished(self, bots: list[BlackjackBotSeat], player_wallet_gold: int) -> bool: + if not self.any_contender_alive(bots): + return True + for h in self.player_hands: + if self.player_hand_needs_turn(h, player_wallet_gold): + return False + for b in bots: + if self.bot_needs_turn(b): + return False + return True + + def any_contender_alive(self, bots: list[BlackjackBotSeat]) -> bool: + return self.any_player_hand_active or any(b.is_active_in_pot for b in bots) + + # --- Dealer Regeln: Zieht bei <= 16, hält ab 17 --- + def dealer_should_hit(self) -> bool: + val, _ = HandEvaluator.evaluate(self.dealer_hand) + return val < BJ_DEALER_STAND + + def dealer_hit(self) -> Card: + card = self.deck.draw() + self.dealer_hand.append(card) + return card + + # --- Showdown & Pot-Abrechnung --- + @staticmethod + def _hand_rank(cards: list[Card], is_split: bool = False) -> tuple[int, int]: + rank = HandEvaluator.showdown_rank(cards) + # Gesplittete 2-Karten-21 zählt regulär als 21 statt Natural Blackjack + if is_split and rank == (2, 21): + return (1, 21) + return rank + + def resolve_showdown(self, bots: list[BlackjackBotSeat]) -> dict: + self.state = "SHOWDOWN" + total_p_bet = self.total_player_bet + + # Solo-Modus ohne Bots (Spielerhände direkt gegen die Bank) + if not bots: + active_p_hands = [h for h in self.player_hands if h.is_active_in_pot] + if not active_p_hands: + return { + "winner_type": "BANK", + "winner_names": [], + "player_payout": 0, + "player_net": -total_p_bet, + "bank_gain": self.pot, + "bot_gains": [], + } + d_rank = self._hand_rank(self.dealer_hand) + payout = 0 + for h in active_p_hands: + hr = self._hand_rank(h.cards, is_split=h.is_split_hand) + if hr > d_rank: + payout += h.bet_in_pot * 2 + elif hr == d_rank: + payout += h.bet_in_pot + net = payout - total_p_bet + w_type = "PLAYER" if net > 0 else ("TIE" if net == 0 else "BANK") + return { + "winner_type": w_type, + "winner_names": [], + "player_payout": payout, + "player_net": net, + "bank_gain": max(0, -net), + "bot_gains": [], + } + + # Multi-Player Vegas-Pot Modus + contenders: list[tuple[str, object, tuple[int, int]]] = [] + for h in self.player_hands: + if h.is_active_in_pot: + contenders.append(("PLAYER", h, self._hand_rank(h.cards, is_split=h.is_split_hand))) + for b in bots: + if b.is_active_in_pot: + contenders.append(("BOT", b, self._hand_rank(b.hand))) + + if not contenders: + return { + "winner_type": "BANK", + "winner_names": [], + "player_payout": 0, + "player_net": -total_p_bet, + "bank_gain": self.pot, + "bot_gains": [], + } + + dealer_rank = self._hand_rank(self.dealer_hand) + best_contender_rank = max(c[2] for c in contenders) + + if dealer_rank > best_contender_rank: + return { + "winner_type": "BANK", + "winner_names": [], + "player_payout": 0, + "player_net": -total_p_bet, + "bank_gain": self.pot, + "bot_gains": [], + } + + if dealer_rank == best_contender_rank: + returned_total = 0 + player_payout = 0 + for kind, obj, rnk in contenders: + if rnk == best_contender_rank: + if kind == "PLAYER": + player_payout += obj.bet_in_pot + else: + obj.gold += obj.bet_in_pot + returned_total += obj.bet_in_pot + + bank_leftover = max(0, self.pot - returned_total) + net = player_payout - total_p_bet + return { + "winner_type": "TIE" if player_payout > 0 and net == 0 else ("BANK" if net < 0 else "TIE"), + "winner_names": [], + "player_payout": player_payout, + "player_net": net, + "bank_gain": bank_leftover, + "bot_gains": [], + } + + winners = [c for c in contenders if c[2] == best_contender_rank] + share = self.pot // len(winners) + remainder = self.pot % len(winners) + + player_won_any = False + player_payout = 0 + bot_win_totals: dict[int, tuple[BlackjackBotSeat, int]] = {} + + for idx, (kind, obj, _rnk) in enumerate(winners): + win_amt = share + (remainder if idx == 0 else 0) + if kind == "PLAYER": + player_won_any = True + player_payout += win_amt + else: + obj.gold += win_amt + prev_amt = bot_win_totals.get(id(obj), (obj, 0))[1] + bot_win_totals[id(obj)] = (obj, prev_amt + win_amt) + + winning_bot_names = [b.name for b, _ in bot_win_totals.values()] + bot_gains = [ + (b.name, tot - b.bet_in_pot) + for b, tot in bot_win_totals.values() + if (tot - b.bet_in_pot) > 0 + ] + + net = player_payout - total_p_bet + return { + "winner_type": "PLAYER" if player_won_any else "BOT", + "winner_names": winning_bot_names, + "player_payout": player_payout, + "player_net": net, + "bank_gain": 0, + "bot_gains": bot_gains, + } \ No newline at end of file diff --git a/games/blackjack/models/bot_ai.py b/games/blackjack/models/bot_ai.py new file mode 100644 index 0000000..cec0bb4 --- /dev/null +++ b/games/blackjack/models/bot_ai.py @@ -0,0 +1,271 @@ +# -*- coding: utf-8 -*- +# games/blackjack/models/bot_ai.py +import random +from games.blackjack.models.bot_seat import BlackjackBotSeat +from games.blackjack.models.hand_evaluator import HandEvaluator +from models.card import Card +from resources.code_res.game_constants import ( + ACE_RANK, BJ_MAX_RAISES_PER_ROUND, BJ_STARTING_GOLD, + BOT_DEITY_LEVEL, FACE_RANKS, SEVEN_RANK +) + + +class BlackjackBotAI: + """ + 4-Stufen-Ablaufbaum KI: + - Stufe 0..5: Abgestufte Offline-Gegner + - Stufe 6 (BOT_DEITY_LEVEL): Entfesselte Gottheit-KI (Online-Standard, kein Kindergarten!) + """ + + def __init__(self): + self.running_count: int = 0 + + @staticmethod + def enforce_online_deity_bots(bot_configs: list[tuple[int, str]]) -> list[tuple[int, str]]: + """Zwingt im Online-Modus ausnahmslos alle Bots auf Gottheit-Niveau (Stufe 6).""" + return [(BOT_DEITY_LEVEL, name) for _lvl, name in bot_configs] + + def reset_count(self): + self.running_count = 0 + + def observe_public_card(self, card: Card): + if card.rank in ("2", "3", "4", "5", "6"): + self.running_count += 1 + elif card.rank in ("10", *FACE_RANKS, ACE_RANK): + self.running_count -= 1 + + def get_true_count(self, remaining_cards: int) -> float: + decks_left = max(0.5, remaining_cards / 52.0) + return self.running_count / decks_left + + def ensure_ante_gold(self, bot: BlackjackBotSeat, min_bet: int, fallback_stack: int = BJ_STARTING_GOLD): + if bot.gold < min_bet: + bot.gold = fallback_stack + bot.rebought = True + else: + bot.rebought = False + + # --- KNOTEN 1: Mitgehen? --- + def decide_step1_mitgehen( + self, bot: BlackjackBotSeat, highest_bet: int, dealer_upcard: Card | None = None, remaining_cards: int = 52 + ) -> bool: + val, is_soft = HandEvaluator.evaluate(bot.hand) + to_call = max(0, highest_bet - bot.bet_in_pot) + lvl = bot.ai_level + + if to_call > 0 and bot.gold > 0: + if lvl == 0: + return random.random() < 0.75 + + # Gottheit-Stufe (6): Rechnet Pot-Odds + Dealer-Upcard + True Count knallhart gegen! + if lvl >= BOT_DEITY_LEVEL: + if val >= 19 or (not is_soft and val in (10, 11)) or is_soft: + return True + up = dealer_upcard.blackjack_value if dealer_upcard else 10 + tc = self.get_true_count(remaining_cards) + # Gegen starke Dealer-Upcard (9, 10, A) mit steifer 14-16 und teurem Raise -> eiskalter Fold + if 13 <= val <= 16 and up >= 8 and to_call >= max(10, highest_bet // 4): + return False + if val == 17 and up >= 10 and to_call >= max(15, highest_bet // 2) and tc < 1.0: + return False + return True + + if val >= 18 or val in (10, 11) or is_soft: + return True + if val <= 16 and to_call >= max(10, highest_bet // 3) and lvl >= 2: + return random.random() < 0.30 + return True + + if bot.cards_locked: + # Gottheit bleibt mit 20/21 im Zug, falls noch Raisedruck aufgebaut werden kann! + if lvl >= BOT_DEITY_LEVEL and val >= 20: + return True + return False + if not is_soft and val >= 19 and 1 <= lvl < BOT_DEITY_LEVEL and random.random() < 0.65: + return False + return True + + # --- KNOTEN 2: Ziehen? (inkl. Double Down Option) --- + def wants_double_down( + self, + bot: BlackjackBotSeat, + dealer_upcard: Card, + highest_bet: int, + raises_in_round: int, + remaining_cards: int = 52, + ) -> bool: + if bot.cards_locked or len(bot.hand) != 2 or bot.ai_level < 2: + return False + if raises_in_round >= BJ_MAX_RAISES_PER_ROUND: + return False + double_cost = max(highest_bet, bot.bet_in_pot) * 2 - bot.bet_in_pot + if bot.gold < double_cost or double_cost <= 0: + return False + + val, is_soft = HandEvaluator.evaluate(bot.hand) + up = dealer_upcard.blackjack_value + + if bot.ai_level >= BOT_DEITY_LEVEL: + tc = self.get_true_count(remaining_cards) + if not is_soft and val == 11 and (up <= 10 or tc >= 1.0): + return True + if not is_soft and val == 10 and (up <= 9 or (up == 10 and tc >= 4.0)): + return True + if not is_soft and val == 9 and (3 <= up <= 6 or (up == 2 and tc >= 1.0)): + return True + if is_soft and val in (17, 18) and 3 <= up <= 6: + return True + return False + + if not is_soft and val == 11 and up <= 10: + return True + if not is_soft and val == 10 and up <= 9 and bot.ai_level >= 3: + return True + return False + + def decide_step2_ziehen( + self, bot: BlackjackBotSeat, dealer_upcard: Card, remaining_cards: int + ) -> bool: + if bot.cards_locked: + return False + val, is_soft = HandEvaluator.evaluate(bot.hand) + up = dealer_upcard.blackjack_value + return self._wants_hit(bot.ai_level, bot.hand, val, is_soft, up, remaining_cards) + + # --- KNOTEN 3: Erhöhen? --- + def decide_step3_erhoehen( + self, + bot: BlackjackBotSeat, + chips: tuple[int, ...], + remaining_cards: int, + raises_in_round: int, + dealer_upcard: Card | None = None, + ) -> int: + if raises_in_round >= BJ_MAX_RAISES_PER_ROUND or bot.gold < chips[0]: + return 0 + val, is_soft = HandEvaluator.evaluate(bot.hand) + lvl = bot.ai_level + + if lvl == 0: + return chips[0] if random.random() < 0.18 else 0 + if lvl == 1: + return chips[0] if val == 21 and random.random() < 0.35 else 0 + if lvl in (2, 3): + return chips[0] if val >= 20 and random.random() < 0.40 else 0 + if lvl == 4: + if val == 21 and random.random() < 0.60: + return min(bot.gold, chips[min(1, len(chips) - 1)]) + if val == 20 and random.random() < 0.35: + return chips[0] + return 0 + + tc = self.get_true_count(remaining_cards) + if lvl == 5: + if val == 21 and random.random() < 0.75: + pick = chips[min(2, len(chips) - 1)] if tc >= 1.5 else chips[min(1, len(chips) - 1)] + return min(bot.gold, pick) + if val == 20 and random.random() < 0.50: + return min(bot.gold, chips[0]) + return 0 + + # --- STUFE 6: GOTTHEIT (Gnadenloser Druck bei Edge!) --- + up = dealer_upcard.blackjack_value if dealer_upcard else 10 + affordable = [c for c in chips if c <= bot.gold] + if not affordable: + return 0 + + if val == 21: + # Mit 21 feuert Gottheit fast immer den höchsten bezahlbaren Chip rein! + return affordable[-1] if tc >= 0.0 else affordable[min(2, len(affordable) - 1)] + if val == 20: + if up <= 9 or tc >= 1.0: + return affordable[min(2, len(affordable) - 1)] + return affordable[0] + if val == 19 and (2 <= up <= 6) and not is_soft: + # Dealer zeigt Bust-Karte (2-6) und Gottheit hält 19 -> Gegner bluten lassen + return affordable[min(1, len(affordable) - 1)] + if (2 <= up <= 6) and val >= 18 and tc >= 2.0: + return affordable[0] + return 0 + + # --- KNOTEN 4: Fertig? --- + def decide_step4_fertig( + self, bot: BlackjackBotSeat, dealer_upcard: Card, remaining_cards: int + ) -> bool: + if bot.cards_locked: + return True + val, is_soft = HandEvaluator.evaluate(bot.hand) + if val >= 21: + return True + up = dealer_upcard.blackjack_value + return not self._wants_hit(bot.ai_level, bot.hand, val, is_soft, up, remaining_cards) + + def _wants_hit( + self, lvl: int, hand: list[Card], val: int, is_soft: bool, up: int, remaining_cards: int + ) -> bool: + if val >= 21: + return False + if len(hand) == 2 and sum(1 for c in hand if c.rank == SEVEN_RANK) == 2 and lvl >= 2: + return True + if lvl == 0: + return val < 20 and random.choice([True, False]) + if lvl == 1: + return val < 15 + if lvl == 2: + return val < 17 + if lvl == 3: + if not is_soft and val >= 13 and 2 <= up <= 6: + return False + return val < 17 + if lvl == 4: + return self._basic_strategy_hit(val, is_soft, up) + + tc = self.get_true_count(remaining_cards) + if lvl == 5: + if not is_soft and val == 16 and up == 10 and tc >= 0.5: + return False + if not is_soft and val == 15 and up == 10 and tc >= 4.0: + return False + if not is_soft and val == 12 and up == 3 and tc >= 2.0: + return False + return self._basic_strategy_hit(val, is_soft, up) + + # --- STUFE 6: GOTTHEIT (Volle Illustrious-18 Index-Abweichungen) --- + if not is_soft: + if val == 16 and up == 10: + return tc < 0.0 + if val == 15 and up == 10: + return tc < 4.0 + if val == 16 and up == 9: + return tc < 5.0 + if val == 13 and up == 2: + return tc < -1.0 + if val == 13 and up == 3: + return tc < -2.0 + if val == 12 and up == 2: + return tc < 3.0 + if val == 12 and up == 3: + return tc < 2.0 + if val == 12 and up == 4: + return tc < 0.0 + if val == 12 and up == 5: + return tc < -2.0 + if val == 12 and up == 6: + return tc < -1.0 + return self._basic_strategy_hit(val, is_soft, up) + + @staticmethod + def _basic_strategy_hit(val: int, is_soft: bool, up: int) -> bool: + if is_soft: + if val >= 19: + return False + if val == 18: + return up >= 9 + return True + if val >= 17: + return False + if 13 <= val <= 16: + return up >= 7 + if val == 12: + return not (4 <= up <= 6) + return True \ No newline at end of file diff --git a/games/blackjack/models/bot_seat.py b/games/blackjack/models/bot_seat.py new file mode 100644 index 0000000..4511850 --- /dev/null +++ b/games/blackjack/models/bot_seat.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +# games/blackjack/models/bot_seat.py +from dataclasses import dataclass, field +from models.card import Card +from resources.code_res.game_constants import BJ_STARTING_GOLD + + +@dataclass +class BlackjackBotSeat: + name: str + ai_level: int + gold: int = BJ_STARTING_GOLD + hand: list[Card] = field(default_factory=list) + bet_in_pot: int = 0 + cards_locked: bool = False + busted: bool = False + folded: bool = False + doubled: bool = False + acted_once: bool = False + status_text: str = "" + rebought: bool = False + + @property + def is_active_in_pot(self) -> bool: + return not self.busted and not self.folded \ No newline at end of file diff --git a/games/blackjack/models/hand_evaluator.py b/games/blackjack/models/hand_evaluator.py new file mode 100644 index 0000000..97548d6 --- /dev/null +++ b/games/blackjack/models/hand_evaluator.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +# games/blackjack/models/hand_evaluator.py +from models.card import Card +from resources.code_res.game_constants import ACE_RANK, BJ_TARGET_SCORE, SEVEN_RANK + + +class HandEvaluator: + @staticmethod + def evaluate(hand: list[Card]) -> tuple[int, bool]: + total = sum(c.blackjack_value for c in hand) + aces = sum(1 for c in hand if c.rank == ACE_RANK) + while total > BJ_TARGET_SCORE and aces > 0: + total -= 10 + aces -= 1 + is_soft = aces > 0 and total <= BJ_TARGET_SCORE + return total, is_soft + + @classmethod + def is_natural_blackjack(cls, hand: list[Card]) -> bool: + val, _ = cls.evaluate(hand) + return len(hand) == 2 and val == BJ_TARGET_SCORE + + @staticmethod + def is_triple_seven(hand: list[Card]) -> bool: + """3 Siebener auf der Hand = Auto-Blackjack & Sofortgewinn!""" + return sum(1 for c in hand if c.rank == SEVEN_RANK) >= 3 + + @classmethod + def showdown_rank(cls, hand: list[Card]) -> tuple[int, int]: + """ + Vergleichswert für den Showdown (nur Hände <= 21): + (3, 21) = 7-7-7 Auto-Blackjack + (2, 21) = Natural Blackjack (2 Karten = 21) + (1, val) = Reguläre Punktzahl <= 21 + (0, 0) = Überkauft (> 21) + """ + val, _ = cls.evaluate(hand) + if cls.is_triple_seven(hand): + return (3, 21) + if val > BJ_TARGET_SCORE: + return (0, 0) + if cls.is_natural_blackjack(hand): + return (2, 21) + return (1, val) \ No newline at end of file diff --git a/games/blackjack/models/player_hand.py b/games/blackjack/models/player_hand.py new file mode 100644 index 0000000..6cf2430 --- /dev/null +++ b/games/blackjack/models/player_hand.py @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- +# games/blackjack/models/player_hand.py +from dataclasses import dataclass, field +from models.card import Card + + +@dataclass +class PlayerHand: + cards: list[Card] = field(default_factory=list) + bet_in_pot: int = 0 + cards_locked: bool = False + busted: bool = False + folded: bool = False + doubled: bool = False + is_split_hand: bool = False + acted_once: bool = False + + @property + def is_active_in_pot(self) -> bool: + return not self.busted and not self.folded \ No newline at end of file diff --git a/games/blackjack/start.py b/games/blackjack/start.py new file mode 100644 index 0000000..1b6ea44 --- /dev/null +++ b/games/blackjack/start.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +# games/blackjack/start.py +from games.blackjack.views.blackjack_menu_view import BlackjackMenuView +from games.blackjack.views.blackjack_table_view import BlackjackTableView +from models.database import Database +from resources.code_res.game_constants import CAT_LUCK + +GAME_TITLE_KEY = "game_title_blackjack" +GAME_FOLDER_ID = "blackjack" +GAME_CATEGORY = CAT_LUCK + + +def start_game(context): + pid = context.profile["id"] + devils_acc = Database.get_active_devils_bj_account(pid) + + if devils_acc is not None: + saved = Database.load_game_state(pid, GAME_FOLDER_ID) + menu_ref = BlackjackMenuView(context) + if saved is not None: + BlackjackTableView( + context, + variant_key=saved["variant_key"], + bj_account_id=devils_acc["id"], + bot_configs=[], + on_back_to_menu=lambda acc_id, msg="": menu_ref.show(preselect_id=acc_id, status_msg=msg), + resume_state_json=saved["state_json"], + ) + else: + saved_bots = Database.load_bot_configs(pid, GAME_FOLDER_ID) + active_bots = [(lvl, name) for _idx, (name, lvl) in sorted(saved_bots.items()) if lvl >= 0] + BlackjackTableView( + context, + variant_key="bj_classic", + bj_account_id=devils_acc["id"], + bot_configs=active_bots, + on_back_to_menu=lambda acc_id, msg="": menu_ref.show(preselect_id=acc_id, status_msg=msg), + ) + return + + Database.delete_game_state(pid, GAME_FOLDER_ID) + BlackjackMenuView(context).show() \ No newline at end of file diff --git a/games/blackjack/views/__pycache__/blackjack_menu_view.cpython-311.pyc b/games/blackjack/views/__pycache__/blackjack_menu_view.cpython-311.pyc new file mode 100644 index 0000000..78c3016 Binary files /dev/null and b/games/blackjack/views/__pycache__/blackjack_menu_view.cpython-311.pyc differ diff --git a/games/blackjack/views/__pycache__/blackjack_table_view.cpython-311.pyc b/games/blackjack/views/__pycache__/blackjack_table_view.cpython-311.pyc new file mode 100644 index 0000000..4f3555b Binary files /dev/null and b/games/blackjack/views/__pycache__/blackjack_table_view.cpython-311.pyc differ diff --git a/games/blackjack/views/__pycache__/round_result_dialog.cpython-311.pyc b/games/blackjack/views/__pycache__/round_result_dialog.cpython-311.pyc new file mode 100644 index 0000000..791319f Binary files /dev/null and b/games/blackjack/views/__pycache__/round_result_dialog.cpython-311.pyc differ diff --git a/games/blackjack/views/blackjack_menu_view.py b/games/blackjack/views/blackjack_menu_view.py new file mode 100644 index 0000000..043020d --- /dev/null +++ b/games/blackjack/views/blackjack_menu_view.py @@ -0,0 +1,449 @@ +# -*- coding: utf-8 -*- +# games/blackjack/views/blackjack_menu_view.py +import sqlite3 +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 models.database import Database +from models.progression import Progression +from resources.code_res.game_constants import ( + ACCENT_GOLD, ACCENT_GOTH, BG_COLOR, BJ_INITIAL_ANTE, BJ_MAX_BOTS, + BJ_STARTING_GOLD, BJ_VARIANTS, BORDER_COLOR, CELL_BG, + DEVILS_DEAL_GOLD_REWARD, ERROR_FG, FG_COLOR, GOLD_MAX_ACCOUNTS, + GOLD_MIN_TABLE_ENTRY, INPUT_BG, MUTED_FG, PANEL_BG, + SUBTLE_BORDER, XP_TO_GOLD_AMOUNT +) +from resources.code_res.i18n import t +from view.widgets.bot_setup_widget import BotSetupWidget +from view.widgets.image_button import ImageButton + +GAME_FOLDER_ID = "blackjack" + + +class BlackjackMenuView: + def __init__(self, context): + self.ctx = context + self.bot_widget: BotSetupWidget | None = None + + def show(self, preselect_id: int | None = None, status_msg: str = "", status_is_ok: bool = False): + pid = self.ctx.profile["id"] + + # Aktiver Devil's Deal zwingt direkt an den Tisch + devils_acc = 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() + self.ctx.root.clear_window(apply_global_bg=True) + bj_prog = self.ctx.refresh_game_progress() + + dyn_xp_cost = bj_prog["xp_exchange_cost"] + is_divine = bj_prog["is_divine_punishment"] + at_floor = bj_prog["at_divine_floor"] + devils_deal_open = bj_prog["devils_deal_unlocked"] + + setting_key = f"last_bj_account_{pid}" + accounts = Database.get_blackjack_accounts(pid) + has_accounts = len(accounts) > 0 + + if preselect_id is None and has_accounts: + saved_id_str = Database.load_setting(setting_key, "") + if saved_id_str.isdigit(): + preselect_id = int(saved_id_str) + + # Im Dropdown stehen nur noch die sauberen Kontonamen; Gold wird prominent separat angezeigt! + acc_by_name = {a["account_name"]: a for a in accounts} + acc_names = list(acc_by_name.keys()) + + active_acc = None + if has_accounts: + 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( + value=active_acc["account_name"] if active_acc else t("bj_no_account_item") + ) + feedback_var = tk.StringVar(value=status_msg) + + def get_current_acc() -> dict | None: + return acc_by_name.get(selected_name_var.get()) + + def open_bj_stats(): + cur = get_current_acc() + if cur is None: + return + if self.bot_widget is not None and has_accounts: + _, to_save = self.bot_widget.collect_configs() + Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save) + BlackjackStatsView( + self.ctx, + on_back_to_bj_menu=lambda aid: self.show(preselect_id=aid) + ).show(selected_acc_id=cur["id"]) + + def refresh_on_lang_switch(): + cur = get_current_acc() + if self.bot_widget is not None and has_accounts: + _, to_save = self.bot_widget.collect_configs() + Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save) + self.show(preselect_id=cur["id"] if cur else None) + + topbar_gold_txt = ( + t("bj_header_gold", active_acc["account_name"], active_acc["gold"]) + if active_acc else "" + ) + topbar = self.ctx.build_game_topbar( + self.ctx.root, + t("bj_menu_topbar"), + on_game_menu=None, + on_stats=open_bj_stats, + stats_enabled=has_accounts, + extra_right_text=topbar_gold_txt, + on_lang_refresh=refresh_on_lang_switch, + ) + + container = tk.Frame(self.ctx.root, bg=BG_COLOR, padx=24, pady=14) + container.place(relx=0.5, rely=0.52, anchor="center", relwidth=0.92, relheight=0.82) + + main_card = tk.Frame( + container, bg=PANEL_BG, padx=24, pady=18, + highlightthickness=1, highlightbackground=BORDER_COLOR + ) + main_card.pack(fill="x") + + upper_split = tk.Frame(main_card, bg=PANEL_BG) + upper_split.pack(fill="x", pady=(0, 12)) + upper_split.columnconfigure(0, weight=1, uniform="cols") + upper_split.columnconfigure(1, weight=1, uniform="cols") + + # ===================================================================== + # SPALTE 1: Goldkonto-Verwaltung (exaktes 3-Spalten-Grid für gleiche Breiten!) + # ===================================================================== + left_col = tk.Frame(upper_split, bg=PANEL_BG) + left_col.grid(row=0, column=0, sticky="nsew", padx=(0, 10)) + + tk.Label( + left_col, + text=t("bj_sec1_title", len(accounts), GOLD_MAX_ACCOUNTS, BJ_STARTING_GOLD), + font=("Georgia", 12, "bold"), fg=ACCENT_GOLD, bg=PANEL_BG + ).pack(anchor="w", pady=(0, 6)) + + acc_box = tk.Frame(left_col, bg=CELL_BG, padx=14, pady=12, highlightthickness=1, highlightbackground=SUBTLE_BORDER) + acc_box.pack(fill="both", expand=True) + + form_grid = tk.Frame(acc_box, bg=CELL_BG) + form_grid.pack(fill="x") + form_grid.columnconfigure(1, weight=1) + + # --- Zeile 0: Aktives Konto (Dropdown + XP-Tausch Button) --- + tk.Label( + form_grid, text=t("bj_active_acc_lbl"), + font=("Helvetica", 10, "bold"), fg=FG_COLOR if has_accounts else MUTED_FG, bg=CELL_BG + ).grid(row=0, column=0, sticky="w", padx=(0, 10), pady=4) + + acc_cb = ttk.Combobox( + form_grid, + textvariable=selected_name_var, + values=acc_names if has_accounts else [t("bj_no_account_item")], + state="readonly" if has_accounts else "disabled", + font=("Helvetica", 10), + style="Goth.TCombobox", + ) + acc_cb.grid(row=0, column=1, sticky="ew", padx=(0, 10), pady=4, ipady=2) + + def exchange_xp_action(): + cur = get_current_acc() + if cur is None: + return + if self.bot_widget is not None: + _, to_save = self.bot_widget.collect_configs() + Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save) + ok, msg = Database.exchange_xp_for_bj_gold(pid, cur["id"]) + if ok and is_divine: + self.ctx.sounds.play("lose") + self.show(preselect_id=cur["id"], status_msg=msg, status_is_ok=ok) + + can_afford_xp = is_divine or (bj_prog["total_points"] >= dyn_xp_cost) + can_exchange = has_accounts and (not at_floor) and can_afford_xp + + ex_btn_txt = ( + t("bj_exchange_divine_btn", f"{dyn_xp_cost:,}".replace(",", "."), XP_TO_GOLD_AMOUNT) + if is_divine else t("bj_exchange_btn", dyn_xp_cost, XP_TO_GOLD_AMOUNT) + ) + exchange_btn = ImageButton( + form_grid, ex_btn_txt, + self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active, + exchange_xp_action, sound_mgr=self.ctx.sounds, + width=185, height=34, font=("Helvetica", 9, "bold"), + enabled=can_exchange, + ) + exchange_btn.grid(row=0, column=2, sticky="e", pady=4) + + # --- Zeile 1: Prominente Gold-Anzeige + Konto löschen --- + gold_banner = tk.Frame( + acc_box, bg=PANEL_BG, padx=12, pady=8, + highlightthickness=1, highlightbackground=BORDER_COLOR if has_accounts else SUBTLE_BORDER + ) + gold_banner.pack(fill="x", pady=(8, 8)) + + gold_var = tk.StringVar( + value=t("bj_gold_display_lbl", active_acc["gold"]) if active_acc else t("bj_gold_display_none") + ) + gold_lbl = tk.Label( + gold_banner, textvariable=gold_var, + font=("Georgia", 13, "bold"), + fg=ACCENT_GOLD if active_acc else MUTED_FG, + bg=PANEL_BG, + ) + gold_lbl.pack(side="left") + + def delete_selected_account(): + cur = get_current_acc() + if cur is not None: + Database.delete_blackjack_account(cur["id"]) + self.show() + + delete_btn = ImageButton( + gold_banner, t("bj_delete_acc_btn"), + self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active, + delete_selected_account, sound_mgr=self.ctx.sounds, + width=120, height=30, font=("Helvetica", 9, "bold"), + enabled=has_accounts, + ) + delete_btn.pack(side="right") + + # --- Zeile 2: Neues Konto anlegen (exakt gleiche Eingabefeld-Breite wie Dropdown oben!) --- + create_grid = tk.Frame(acc_box, bg=CELL_BG) + create_grid.pack(fill="x") + create_grid.columnconfigure(1, weight=1) + # Unsichtbarer Platzhalter hält Spalte 0 exakt so breit wie "Aktives Konto:" oben + lbl_w = max(len(t("bj_active_acc_lbl")), len(t("bj_new_acc_lbl"))) + form_grid.grid_slaves(row=0, column=0)[0].configure(width=lbl_w, anchor="w") + + can_create_more = len(accounts) < GOLD_MAX_ACCOUNTS + tk.Label( + create_grid, text=t("bj_new_acc_lbl"), width=lbl_w, anchor="w", + font=("Helvetica", 10, "bold" if not has_accounts else "normal"), + fg=ACCENT_GOLD if not has_accounts else (FG_COLOR if can_create_more else MUTED_FG), + bg=CELL_BG, + ).grid(row=0, column=0, sticky="w", padx=(0, 10), pady=4) + + next_idx = len(accounts) + 1 + new_acc_var = tk.StringVar( + value=t("bj_default_acc_name", next_idx) if can_create_more else t("bj_max_acc_reached", GOLD_MAX_ACCOUNTS) + ) + new_entry = tk.Entry( + create_grid, textvariable=new_acc_var, font=("Helvetica", 10), + bg=INPUT_BG, fg=FG_COLOR, disabledbackground="#16141c", disabledforeground="#666070", + bd=0, highlightthickness=1, highlightbackground=ACCENT_GOLD if not has_accounts else BORDER_COLOR, + insertbackground="white", state="normal" if can_create_more else "disabled" + ) + new_entry.grid(row=0, column=1, sticky="ew", padx=(0, 10), pady=4, ipady=5) + + def create_new_account(): + if not can_create_more: + return + name = new_acc_var.get().strip() + if not name: + feedback_var.set(t("bj_err_empty_name")) + return + try: + if self.bot_widget is not None and has_accounts: + _, to_save = self.bot_widget.collect_configs() + Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save) + created = Database.create_blackjack_account(pid, name) + Database.save_setting(setting_key, str(created["id"])) + self.show(preselect_id=created["id"]) + except (sqlite3.IntegrityError, RuntimeError) as exc: + feedback_var.set(t("bj_err_duplicate_name") if isinstance(exc, sqlite3.IntegrityError) else str(exc)) + + if can_create_more: + new_entry.bind("", 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("<>", on_account_switched) \ No newline at end of file diff --git a/games/blackjack/views/blackjack_stats_view.py b/games/blackjack/views/blackjack_stats_view.py new file mode 100644 index 0000000..d6f85ff --- /dev/null +++ b/games/blackjack/views/blackjack_stats_view.py @@ -0,0 +1,85 @@ +# -*- 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") \ No newline at end of file diff --git a/games/blackjack/views/blackjack_table_view.py b/games/blackjack/views/blackjack_table_view.py new file mode 100644 index 0000000..91652ba --- /dev/null +++ b/games/blackjack/views/blackjack_table_view.py @@ -0,0 +1,1112 @@ +# -*- coding: utf-8 -*- +# games/blackjack/views/blackjack_table_view.py +import json +import time +import tkinter as tk + +from games.blackjack.models.blackjack_engine import BlackjackEngine +from games.blackjack.models.bot_ai import BlackjackBotAI +from games.blackjack.models.bot_seat import BlackjackBotSeat +from games.blackjack.models.hand_evaluator import HandEvaluator +from games.blackjack.models.player_hand import PlayerHand +from games.blackjack.views.round_result_dialog import BlackjackResultDialog +from models.database import Database +from models.progression import Progression +from resources.code_res.game_constants import ( + ACCENT_GOLD, ACCENT_GOTH, BJ_BOT_CARD_SIZE, BJ_BOT_TURN_DELAY_MS, + BJ_DEALER_DELAY_MS, BJ_INITIAL_ANTE, BJ_MAX_RAISES_PER_ROUND, + BJ_SPLIT_CARD_SIZE, BJ_STARTING_GOLD, BJ_VARIANTS, BORDER_COLOR, + CELL_BG, ERROR_FG, FG_COLOR, GOLD_MIN_TABLE_ENTRY, MUTED_FG, + PANEL_BG, PLAYING_CARD_SIZE, SUBTLE_BORDER, TABLE_BG, XP_TO_GOLD_AMOUNT +) +from resources.code_res.i18n import t +from view.widgets.image_button import ImageButton + +GAME_FOLDER_ID = "blackjack" + +STEP_MITGEHEN = "MITGEHEN" +STEP_ZIEHEN = "ZIEHEN" +STEP_ERHOEHEN = "ERHOEHEN" +STEP_FERTIG = "FERTIG" + + +class BlackjackTableView: + def __init__( + self, + context, + variant_key: str, + bj_account_id: int, + bot_configs: list[tuple[int, str]], + on_back_to_menu, + resume_state_json: str | None = None, + ): + self.ctx = context + self.variant_key = variant_key + self.cfg = BJ_VARIANTS[variant_key] + self.on_back_to_menu = on_back_to_menu + self.engine = BlackjackEngine(num_decks=self.cfg["decks"]) + self.bot_ai = BlackjackBotAI() + + self.active_hand_idx: int = 0 + self.turn_step: str = STEP_MITGEHEN + self.active_bot_idx: int = -1 + self.round_start_time: float = time.time() + self._last_popup_payload: dict | None = None + self._result_dialog: BlackjackResultDialog | None = None + self._photo_refs = [] + self._turn_job = None + + self.ctx.sounds.play_ingame_music() + + if resume_state_json is not None: + self._restore_from_json(resume_state_json) + else: + self.bj_account = Database.get_blackjack_account(bj_account_id) + self.devils_locked = bool(self.bj_account.get("devils_deal_active", 0)) + + level_chips = self._get_current_level_chips() + bot_bankroll = max(BJ_STARTING_GOLD, level_chips[-1] * 4) + self.bots: list[BlackjackBotSeat] = [ + BlackjackBotSeat(name=b_name, ai_level=lvl, gold=bot_bankroll) + for lvl, b_name in bot_configs + ] + self._build_ui() + self._start_new_round() + + # --------------------------------------------------------- + # AUTO-SAVE & RESUME (speichert auch den exakten Baum-Knoten!) + # --------------------------------------------------------- + def _persist_state(self): + if not self.devils_locked: + return + state_obj = { + "bj_account_id": self.bj_account["id"], + "devils_locked": self.devils_locked, + "active_hand_idx": self.active_hand_idx, + "turn_step": self.turn_step, + "active_bot_idx": self.active_bot_idx, + "elapsed_sec": max(0.0, time.time() - self.round_start_time), + "running_count": self.bot_ai.running_count, + "last_popup_payload": self._last_popup_payload, + "engine": self.engine.to_dict(self.bots), + } + Database.save_game_state( + self.ctx.profile["id"], + GAME_FOLDER_ID, + self.variant_key, + json.dumps(state_obj), + ) + + def _clear_persisted_state(self): + Database.delete_game_state(self.ctx.profile["id"], GAME_FOLDER_ID) + + def _restore_from_json(self, raw_json: str): + try: + data = json.loads(raw_json) + self.bj_account = Database.get_blackjack_account(data["bj_account_id"]) + self.devils_locked = bool(data.get("devils_locked", False) or self.bj_account.get("devils_deal_active", 0)) + self.active_hand_idx = int(data.get("active_hand_idx", 0)) + self.turn_step = data.get("turn_step", STEP_MITGEHEN) + self.active_bot_idx = int(data.get("active_bot_idx", -1)) + self.round_start_time = time.time() - float(data.get("elapsed_sec", 0.0)) + self.bot_ai.running_count = int(data.get("running_count", 0)) + self._last_popup_payload = data.get("last_popup_payload") + self.bots = self.engine.load_from_dict(data["engine"]) + except Exception: + self._clear_persisted_state() + dev_acc = Database.get_active_devils_bj_account(self.ctx.profile["id"]) + accounts = Database.get_blackjack_accounts(self.ctx.profile["id"]) + self.bj_account = dev_acc or accounts[0] + self.devils_locked = bool(self.bj_account.get("devils_deal_active", 0)) + self.bots = [] + self._build_ui() + self._start_new_round() + return + + self._build_ui() + + if self.engine.state == "ACTION_LOOP": + if self.active_bot_idx >= 0: + self._render_table(reveal_opponents=False, reveal_dealer=False) + self._step_next_bot() + else: + self._render_table(reveal_opponents=False, reveal_dealer=False) + if 0 <= self.active_hand_idx < len(self.engine.player_hands) and self.engine.player_hand_needs_turn( + self.engine.player_hands[self.active_hand_idx], self.bj_account["gold"] + ): + self._render_current_tree_step() + else: + self._begin_next_turn_cycle() + elif self.engine.state == "DEALER_TURN": + self._render_table(reveal_opponents=True, reveal_dealer=True) + self.status_lbl.configure(text=t("bj_dealer_reveals")) + self._turn_job = self.ctx.root.after(BJ_DEALER_DELAY_MS, self._dealer_draw_step) + elif self.engine.state == "SHOWDOWN" and self._last_popup_payload: + self._render_table(reveal_opponents=True, reveal_dealer=True) + self._open_result_popup(self._build_localized_popup_data(self._last_popup_payload)) + else: + self._start_new_round() + + def _get_current_level_chips(self) -> tuple[int, int, int, int]: + bj_lvl = self.ctx.game_progress["level"] + return Progression.get_level_bet_chips(bj_lvl, bet_scale=self.cfg.get("bet_scale", 1)) + + def _cleanup_and_go(self, nav_callable): + if self.devils_locked: + return + if self._turn_job: + try: + self.ctx.root.after_cancel(self._turn_job) + except Exception: + pass + self._turn_job = None + if self._result_dialog: + self._result_dialog.close_dialog() + self._result_dialog = None + self._clear_persisted_state() + nav_callable() + + def _on_language_switched(self): + self._persist_state() + self._build_ui() + if self.engine.state == "ACTION_LOOP": + self._render_table(reveal_opponents=False, reveal_dealer=False) + if self.active_bot_idx == -1: + self._render_current_tree_step() + elif self.engine.state == "DEALER_TURN": + self._render_table(reveal_opponents=True, reveal_dealer=True) + self.status_lbl.configure(text=t("bj_dealer_reveals")) + elif self.engine.state == "SHOWDOWN" and self._last_popup_payload: + self._render_table(reveal_opponents=True, reveal_dealer=True) + self._open_result_popup(self._build_localized_popup_data(self._last_popup_payload)) + + def _build_ui(self): + if self._result_dialog: + self._result_dialog.close_dialog() + self._result_dialog = None + + self.ctx.root.clear_window(apply_global_bg=True) + + self.topbar = self.ctx.build_game_topbar( + self.ctx.root, + t(f"variant_{self.variant_key}"), + on_game_menu=lambda: self._cleanup_and_go(lambda: self.on_back_to_menu(self.bj_account["id"])), + on_lang_refresh=self._on_language_switched, + locked_exit=self.devils_locked, + ) + + self.table_frame = tk.Frame( + self.ctx.root, bg=TABLE_BG, padx=18, pady=8, + highlightthickness=1, highlightbackground=ERROR_FG if self.devils_locked else BORDER_COLOR + ) + self.table_frame.place(relx=0.5, rely=0.53, anchor="center", relwidth=0.94, relheight=0.86) + + self.pot_lbl = tk.Label( + self.table_frame, text="", font=("Georgia", 12, "bold"), + fg=ACCENT_GOLD, bg=PANEL_BG, pady=4, highlightthickness=1, highlightbackground=SUBTLE_BORDER + ) + self.pot_lbl.pack(fill="x", pady=(0, 4)) + + dealer_sec = tk.Frame(self.table_frame, bg=TABLE_BG) + dealer_sec.pack(fill="x", pady=(2, 2)) + self.dealer_lbl = tk.Label(dealer_sec, text=t("bj_dealer_title"), font=("Georgia", 11, "bold"), fg=MUTED_FG, bg=TABLE_BG) + self.dealer_lbl.pack() + self.dealer_cards_frame = tk.Frame(dealer_sec, bg=TABLE_BG, height=148) + self.dealer_cards_frame.pack(pady=2) + + mid_sec = tk.Frame(self.table_frame, bg=TABLE_BG) + mid_sec.pack(fill="x") + self.status_lbl = tk.Label(mid_sec, text="", font=("Georgia", 11, "bold"), fg=ACCENT_GOLD, bg=TABLE_BG) + self.status_lbl.pack(pady=4) + + seats_area = tk.Frame(self.table_frame, bg=TABLE_BG) + seats_area.pack(fill="both", expand=True, pady=(2, 4)) + + if self.bots: + self.bots_row = tk.Frame(seats_area, bg=TABLE_BG) + self.bots_row.pack(side="left", fill="y", padx=(0, 14)) + else: + self.bots_row = None + + self.player_sec = tk.Frame(seats_area, bg=TABLE_BG) + self.player_sec.pack(side="left", fill="both", expand=True) + + self.controls_frame = tk.Frame( + self.table_frame, bg=PANEL_BG, padx=14, pady=10, + highlightthickness=1, highlightbackground=SUBTLE_BORDER + ) + self.controls_frame.pack(fill="x", side="bottom") + self._refresh_header() + + def _refresh_header(self): + self.bj_account = Database.get_blackjack_account(self.bj_account["id"]) + prof = self.ctx.profile + prog = self.ctx.refresh_game_progress() + self.topbar.extra_label.configure(text=t("bj_header_gold", self.bj_account["account_name"], self.bj_account["gold"])) + self.topbar.level_label.configure( + text=t("level_badge", prof["name"], prog["title"], prog["level"], prog["current_xp"], prog["needed_xp"]) + ) + self.pot_lbl.configure(text=t("bj_pot_banner", self.engine.pot, self.engine.highest_bet)) + + # --------------------------------------------------------- + # ROUND START (10 Gold Grundeinsatz -> Karten verteilen) + # --------------------------------------------------------- + def _start_new_round(self): + if self._result_dialog: + self._result_dialog.close_dialog() + self._result_dialog = None + + self.bj_account = Database.get_blackjack_account(self.bj_account["id"]) + self.devils_locked = bool(self.bj_account.get("devils_deal_active", 0)) + gold = self.bj_account["gold"] + + if gold < GOLD_MIN_TABLE_ENTRY: + Database.set_bj_devils_deal_active(self.bj_account["id"], False) + self.devils_locked = False + self._clear_persisted_state() + cur_cost = self.ctx.refresh_game_progress()["xp_exchange_cost"] + msg = t( + "bj_err_not_enough_gold_entry", + self.bj_account["account_name"], GOLD_MIN_TABLE_ENTRY, gold, + cur_cost, XP_TO_GOLD_AMOUNT + ) + self._cleanup_and_go(lambda: self.on_back_to_menu(self.bj_account["id"], msg)) + return + + self._last_popup_payload = None + self.active_hand_idx = 0 + self.turn_step = STEP_MITGEHEN + self.active_bot_idx = -1 + self.round_start_time = time.time() + self.ctx.sounds.play("deal") + + min_cards = (len(self.bots) + 3) * 6 + if self.engine.check_reshuffle(min_needed=min_cards): + self.bot_ai.reset_count() + + level_chips = self._get_current_level_chips() + min_bot_stack = max(BJ_STARTING_GOLD, level_chips[-1] * 3) + for b in self.bots: + self.bot_ai.ensure_ante_gold(b, BJ_INITIAL_ANTE, fallback_stack=min_bot_stack) + + paid_ante = self.engine.deal_initial_round(BJ_INITIAL_ANTE, gold, self.bots) + self.bj_account = Database.update_blackjack_gold(self.bj_account["id"], -paid_ante) + + self.bot_ai.observe_public_card(self.engine.dealer_hand[0]) + self._persist_state() + + self._build_ui() + self._render_table(reveal_opponents=False, reveal_dealer=False) + self._begin_next_turn_cycle() + + # --------------------------------------------------------- + # RENDERING TISCH & HÄNDE + # --------------------------------------------------------- + @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.cards_locked: + return t("bj_state_locked") + return "" + + def _render_bots(self, reveal_opponents: bool): + if not self.bots_row or not self.bots_row.winfo_exists(): + return + for w in self.bots_row.winfo_children(): + w.destroy() + + for idx, bot in enumerate(self.bots): + is_turn = (idx == self.active_bot_idx) + border_col = ACCENT_GOLD if is_turn else (ERROR_FG if (bot.busted or bot.folded) else SUBTLE_BORDER) + box = tk.Frame( + self.bots_row, bg=CELL_BG, padx=8, pady=5, + highlightthickness=2 if is_turn else 1, highlightbackground=border_col + ) + box.pack(side="left", padx=4, fill="y") + + disp_name = t("bj_bot_rebuy", bot.name) if bot.rebought else bot.name + tk.Label(box, text=disp_name, font=("Georgia", 10, "bold"), fg=ACCENT_GOTH, bg=CELL_BG).pack() + tk.Label(box, text=t("bj_bot_gold_lbl", bot.gold), font=("Helvetica", 9, "bold"), fg=ACCENT_GOLD, bg=CELL_BG).pack() + + cards_f = tk.Frame(box, bg=CELL_BG, height=96) + cards_f.pack(pady=3) + + show_faces = reveal_opponents or bot.busted + for card in bot.hand: + photo = ( + self.ctx.assets.get_card_photo(card.image_filename, size=BJ_BOT_CARD_SIZE) + if show_faces + else self.ctx.assets.get_card_back_photo(color=self.cfg["back_color"], size=BJ_BOT_CARD_SIZE) + ) + if photo: + self._photo_refs.append(photo) + tk.Label(cards_f, image=photo, bg=CELL_BG, bd=0).pack(side="left", padx=2) + + if reveal_opponents and bot.hand and bot.is_active_in_pot: + b_val, _ = HandEvaluator.evaluate(bot.hand) + 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 = "" + + tk.Label( + box, text=info_txt, font=("Helvetica", 9, "bold" if bot.busted else "normal"), + fg=ERROR_FG if (bot.busted or bot.folded) else FG_COLOR, bg=CELL_BG + ).pack() + + def _render_player_hands(self): + for w in self.player_sec.winfo_children(): + w.destroy() + + hands = self.engine.player_hands + if not hands: + return + + if len(hands) == 1: + h = hands[0] + cards_f = tk.Frame(self.player_sec, bg=TABLE_BG, height=150) + cards_f.pack(pady=3) + for card in h.cards: + photo = self.ctx.assets.get_card_photo(card.image_filename, size=PLAYING_CARD_SIZE) + if photo: + self._photo_refs.append(photo) + tk.Label(cards_f, image=photo, bg=TABLE_BG, bd=0).pack(side="left", padx=4) + + p_val, p_soft = HandEvaluator.evaluate(h.cards) + soft_hint = t("bj_soft_hint", p_val) if p_soft and p_val < 21 else "" + suffix = self._hand_state_suffix(h) + lbl_col = ERROR_FG if (h.busted or h.folded) else FG_COLOR + tk.Label( + self.player_sec, + text=t("bj_player_total", p_val, soft_hint, h.bet_in_pot, suffix), + font=("Georgia", 12, "bold"), fg=lbl_col, bg=TABLE_BG + ).pack() + return + + split_wrap = tk.Frame(self.player_sec, bg=TABLE_BG) + split_wrap.pack(expand=True) + + for idx, h in enumerate(hands): + is_active = (self.engine.state == "ACTION_LOOP" and self.active_bot_idx == -1 and idx == self.active_hand_idx) + b_col = ACCENT_GOLD if is_active else (ERROR_FG if (h.busted or h.folded) else SUBTLE_BORDER) + hbox = tk.Frame( + split_wrap, bg=CELL_BG, padx=10, pady=6, + highlightthickness=2 if is_active else 1, highlightbackground=b_col + ) + hbox.pack(side="left", padx=8) + + cards_f = tk.Frame(hbox, bg=CELL_BG, height=126) + cards_f.pack(pady=2) + for card in h.cards: + photo = self.ctx.assets.get_card_photo(card.image_filename, size=BJ_SPLIT_CARD_SIZE) + if photo: + self._photo_refs.append(photo) + tk.Label(cards_f, image=photo, bg=CELL_BG, bd=0).pack(side="left", padx=3) + + p_val, p_soft = HandEvaluator.evaluate(h.cards) + soft_hint = t("bj_soft_hint", p_val) if p_soft and p_val < 21 else "" + suffix = self._hand_state_suffix(h) + lbl_col = ACCENT_GOLD if is_active else (ERROR_FG if (h.busted or h.folded) else FG_COLOR) + tk.Label( + hbox, + text=t("bj_hand_box_title", idx + 1, p_val, soft_hint, h.bet_in_pot, suffix), + font=("Georgia", 10, "bold"), fg=lbl_col, bg=CELL_BG + ).pack(pady=(2, 0)) + + def _render_table(self, reveal_opponents: bool, reveal_dealer: bool): + self._photo_refs.clear() + for w in self.dealer_cards_frame.winfo_children(): + w.destroy() + + for idx, card in enumerate(self.engine.dealer_hand): + photo = ( + self.ctx.assets.get_card_back_photo(color=self.cfg["back_color"], size=PLAYING_CARD_SIZE) + if idx == 1 and not reveal_dealer + else self.ctx.assets.get_card_photo(card.image_filename, size=PLAYING_CARD_SIZE) + ) + if photo: + self._photo_refs.append(photo) + tk.Label(self.dealer_cards_frame, image=photo, bg=TABLE_BG, bd=0).pack(side="left", padx=5) + + if not reveal_dealer and self.engine.dealer_hand: + up_val, _ = HandEvaluator.evaluate([self.engine.dealer_hand[0]]) + self.dealer_lbl.configure(text=t("bj_dealer_shows", up_val)) + elif self.engine.dealer_hand: + d_val, _ = HandEvaluator.evaluate(self.engine.dealer_hand) + self.dealer_lbl.configure(text=t("bj_dealer_total", d_val)) + + self._render_player_hands() + self._render_bots(reveal_opponents=reveal_opponents) + self._refresh_header() + + # --------------------------------------------------------- + # STUFENWEISER ABLAUFBAUM FÜR DEN SPIELER + # --------------------------------------------------------- + def _begin_next_turn_cycle(self): + self.bj_account = Database.get_blackjack_account(self.bj_account["id"]) + if self.engine.is_everyone_finished(self.bots, self.bj_account["gold"]): + self._start_showdown_and_dealer() + return + + self.active_bot_idx = -1 + self.active_hand_idx = 0 + self._step_next_player_hand() + + def _step_next_player_hand(self): + self.bj_account = Database.get_blackjack_account(self.bj_account["id"]) + wallet = self.bj_account["gold"] + + while self.active_hand_idx < len(self.engine.player_hands): + h = self.engine.player_hands[self.active_hand_idx] + if self.engine.player_hand_needs_turn(h, wallet): + self.turn_step = STEP_MITGEHEN + self._persist_state() + self._render_table(reveal_opponents=False, reveal_dealer=False) + self._render_current_tree_step() + return + self.active_hand_idx += 1 + + # Alle eigenen Hände durch -> sofort der nächste Gegner dran! + self._start_bots_cycle() + + def _finish_current_hand_turn(self): + self.active_hand_idx += 1 + self.turn_step = STEP_MITGEHEN + self._persist_state() + self._step_next_player_hand() + + def _render_current_tree_step(self): + for w in self.controls_frame.winfo_children(): + w.destroy() + + self.bj_account = Database.get_blackjack_account(self.bj_account["id"]) + wallet = self.bj_account["gold"] + hand = self.engine.player_hands[self.active_hand_idx] + hand_tag = t("bj_active_hand_tag", self.active_hand_idx + 1) if len(self.engine.player_hands) > 1 else "" + + row = tk.Frame(self.controls_frame, bg=PANEL_BG) + row.pack() + + # ===================================================== + # KNOTEN 1: MITGEHEN? + # ===================================================== + if self.turn_step == STEP_MITGEHEN: + raw_deficit = max(0, self.engine.highest_bet - hand.bet_in_pot) + to_call = min(wallet, raw_deficit) + + if to_call > 0: + self.status_lbl.configure(text=t("bj_tree_step1_call", hand_tag, to_call)) + ImageButton( + row, t("bj_tree_btn_call_yes", to_call), + self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active, + lambda: self._on_step1_yes(to_call), + sound_mgr=self.ctx.sounds, width=215, height=38, font=("Helvetica", 10, "bold") + ).pack(side="left", padx=8) + + ImageButton( + row, t("bj_tree_btn_call_no_lose"), + self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active, + self._on_step1_no_when_raised, + sound_mgr=self.ctx.sounds, width=225, height=38, font=("Helvetica", 10, "bold") + ).pack(side="left", padx=8) + else: + self.status_lbl.configure(text=t("bj_tree_step1_even", hand_tag)) + ImageButton( + row, t("bj_tree_btn_play_yes"), + self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active, + lambda: self._on_step1_yes(0), + sound_mgr=self.ctx.sounds, width=235, height=38, font=("Helvetica", 10, "bold") + ).pack(side="left", padx=8) + + ImageButton( + row, t("bj_tree_btn_even_no_done"), + self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active, + self._on_step1_no_mark_ready, + sound_mgr=None, width=225, height=38, font=("Helvetica", 10, "bold") + ).pack(side="left", padx=8) + + ImageButton( + row, t("bj_fold_btn"), + self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active, + self._on_step1_no_when_raised, + sound_mgr=self.ctx.sounds, width=130, height=38, font=("Helvetica", 10, "bold") + ).pack(side="left", padx=8) + return + + # ===================================================== + # KNOTEN 2: ZIEHEN? (inkl. Split / Double Down bei 2 Karten) + # ===================================================== + if self.turn_step == STEP_ZIEHEN: + self.status_lbl.configure(text=t("bj_tree_step2_draw", hand_tag)) + + ImageButton( + row, t("bj_tree_btn_draw_yes"), + self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active, + self._on_step2_draw_yes, + sound_mgr=self.ctx.sounds, width=185, height=38, font=("Helvetica", 10, "bold") + ).pack(side="left", padx=6) + + if self.engine.can_double_down(self.active_hand_idx, wallet, already_drew_this_turn=False): + dd_cost = self.engine.get_double_down_cost(self.active_hand_idx) + ImageButton( + row, t("bj_double_btn", dd_cost), + self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active, + self._on_step2_double_down, + sound_mgr=self.ctx.sounds, width=175, height=38, font=("Helvetica", 10, "bold") + ).pack(side="left", padx=6) + + if self.engine.can_split_hand(self.active_hand_idx, wallet): + sp_cost = self.engine.highest_bet + ImageButton( + row, t("bj_split_btn", sp_cost), + self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active, + self._on_step2_split, + sound_mgr=self.ctx.sounds, width=150, height=38, font=("Helvetica", 10, "bold") + ).pack(side="left", padx=6) + + ImageButton( + row, t("bj_tree_btn_draw_no"), + self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active, + self._on_step2_draw_no, + sound_mgr=self.ctx.sounds, width=180, height=38, font=("Helvetica", 10, "bold") + ).pack(side="left", padx=6) + return + + # ===================================================== + # KNOTEN 3: ERHÖHEN? (erst NACH Weiter/Ziehen sichtbar!) + # ===================================================== + if self.turn_step == STEP_ERHOEHEN: + self.status_lbl.configure(text=t("bj_tree_step3_raise", hand_tag)) + dyn_chips = self._get_current_level_chips() + + for chip in dyn_chips: + if wallet >= chip: + ImageButton( + row, f"+{chip} Gold", + self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active, + lambda c=chip: self._on_step3_raise_yes(c), + sound_mgr=self.ctx.sounds, width=115, height=38, font=("Helvetica", 10, "bold") + ).pack(side="left", padx=5) + + ImageButton( + row, t("bj_tree_btn_raise_no"), + self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active, + self._on_step3_raise_no, + sound_mgr=self.ctx.sounds, width=190, height=38, font=("Helvetica", 10, "bold") + ).pack(side="left", padx=8) + return + + # ===================================================== + # KNOTEN 4: FERTIG? + # ===================================================== + if self.turn_step == STEP_FERTIG: + self.status_lbl.configure(text=t("bj_tree_step4_done", hand_tag)) + + ImageButton( + row, t("bj_tree_btn_done_yes"), + self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active, + self._on_step4_done_yes, + sound_mgr=None, width=225, height=38, font=("Helvetica", 10, "bold") + ).pack(side="left", padx=8) + + ImageButton( + row, t("bj_tree_btn_done_no"), + self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active, + self._on_step4_done_no, + sound_mgr=self.ctx.sounds, width=230, height=38, font=("Helvetica", 10, "bold") + ).pack(side="left", padx=8) + + # --------------------------------------------------------- + # ÜBERGÄNGE ZWISCHEN DEN BAUM-KNOTEN + # --------------------------------------------------------- + def _advance_to_erhoehen_or_fertig(self): + """Springt zu Knoten 3 (Erhöhen?), oder direkt weiter, falls kein Gold/Raise-Cap mehr frei ist.""" + self.bj_account = Database.get_blackjack_account(self.bj_account["id"]) + wallet = self.bj_account["gold"] + dyn_chips = self._get_current_level_chips() + can_raise = (self.engine.raises_in_round < BJ_MAX_RAISES_PER_ROUND) and (wallet >= dyn_chips[0]) + + if can_raise: + self.turn_step = STEP_ERHOEHEN + self._persist_state() + self._render_current_tree_step() + else: + self._advance_to_fertig_or_next() + + def _advance_to_fertig_or_next(self): + """Springt zu Knoten 4 (Fertig?), oder gibt direkt an den nächsten Spieler ab, falls Karten schon feststehen.""" + hand = self.engine.player_hands[self.active_hand_idx] + if hand.cards_locked: + self._finish_current_hand_turn() + else: + self.turn_step = STEP_FERTIG + self._persist_state() + self._render_current_tree_step() + + def _on_step1_yes(self, to_call: int): + """Knoten 1 -> Ja (Mitgehen): Zahlt ggf. Differenz ein und geht zu Knoten 2 (Ziehen?).""" + if to_call > 0: + paid = self.engine.player_add_gold_to_pot(self.active_hand_idx, to_call) + if paid > 0: + self.bj_account = Database.update_blackjack_gold(self.bj_account["id"], -paid) + + hand = self.engine.player_hands[self.active_hand_idx] + hand.acted_once = True + h_val, _ = HandEvaluator.evaluate(hand.cards) + + if not hand.cards_locked and h_val < 21: + self.turn_step = STEP_ZIEHEN + self._persist_state() + self._render_table(reveal_opponents=False, reveal_dealer=False) + self._render_current_tree_step() + else: + # Karten standen bereits fest (z.B. 21 oder vorher Fertig gemeldet) -> weiter zu Erhöhen? / Nächster! + self._render_table(reveal_opponents=False, reveal_dealer=False) + self._advance_to_erhoehen_or_fertig() + + def _on_step1_no_mark_ready(self): + """Knoten 1 -> Nein (ohne offenen Raise): Spieler wird als Fertig markiert -> direkt Nächster dran!""" + self.ctx.sounds.play("stand") + hand = self.engine.player_hands[self.active_hand_idx] + hand.cards_locked = True + hand.acted_once = True + self._render_table(reveal_opponents=False, reveal_dealer=False) + self._finish_current_hand_turn() + + def _on_step1_no_when_raised(self): + """Knoten 1 -> Nein gegen Erhöhung / Austreten: Sofort Verloren (Out) -> Nächster dran!""" + hand = self.engine.player_hands[self.active_hand_idx] + hand.folded = True + hand.cards_locked = True + hand.acted_once = True + self._render_table(reveal_opponents=False, reveal_dealer=False) + self._finish_current_hand_turn() + + def _on_step2_draw_yes(self): + """Knoten 2 -> Ja (Ziehen!): Zieht Karte -> über 21 = Verloren, sonst zu Knoten 3 (Erhöhen?).""" + hand = self.engine.player_hands[self.active_hand_idx] + self.engine.player_draw_card(self.active_hand_idx) + + if HandEvaluator.is_triple_seven(hand.cards): + self._trigger_instant_777_win(winner_is_player=True, winning_bot=None) + return + + self._render_table(reveal_opponents=False, reveal_dealer=False) + if hand.busted: + # Über 21 -> sofort Verloren & nächster Spieler dran! + self._finish_current_hand_turn() + return + + self._advance_to_erhoehen_or_fertig() + + def _on_step2_draw_no(self): + """Knoten 2 -> Nein (Nicht ziehen): Direkt weiter zu Knoten 3 (Erhöhen?).""" + self._advance_to_erhoehen_or_fertig() + + def _on_step2_double_down(self): + paid, _card = self.engine.double_down_player_hand(self.active_hand_idx) + if paid > 0: + self.bj_account = Database.update_blackjack_gold(self.bj_account["id"], -paid) + + hand = self.engine.player_hands[self.active_hand_idx] + if HandEvaluator.is_triple_seven(hand.cards): + self._trigger_instant_777_win(winner_is_player=True, winning_bot=None) + return + + self._render_table(reveal_opponents=False, reveal_dealer=False) + self._finish_current_hand_turn() + + def _on_step2_split(self): + paid = self.engine.split_player_hand() + if paid > 0: + self.bj_account = Database.update_blackjack_gold(self.bj_account["id"], -paid) + self.active_hand_idx = 0 + self.turn_step = STEP_ZIEHEN + self._persist_state() + self._render_table(reveal_opponents=False, reveal_dealer=False) + self._render_current_tree_step() + + def _on_step3_raise_yes(self, chip_amount: int): + """Knoten 3 -> Ja (Erhöhen!): Erhöht den Pot und übergibt laut Baum direkt an Next round / nächsten Spieler!""" + paid = self.engine.player_add_gold_to_pot(self.active_hand_idx, chip_amount) + if paid > 0: + self.bj_account = Database.update_blackjack_gold(self.bj_account["id"], -paid) + self._render_table(reveal_opponents=False, reveal_dealer=False) + self._finish_current_hand_turn() + + def _on_step3_raise_no(self): + """Knoten 3 -> Nein: Weiter zu Knoten 4 (Fertig?).""" + self._advance_to_fertig_or_next() + + def _on_step4_done_yes(self): + """Knoten 4 -> Ja (Fertig): Karten stehen endgültig fest -> Nächster dran!""" + self.ctx.sounds.play("stand") + hand = self.engine.player_hands[self.active_hand_idx] + hand.cards_locked = True + self._render_table(reveal_opponents=False, reveal_dealer=False) + self._finish_current_hand_turn() + + def _on_step4_done_no(self): + """Knoten 4 -> Nein (Offen bleiben): Direkt der Nächste dran!""" + self._finish_current_hand_turn() + + # --------------------------------------------------------- + # BOT-ZYKLUS (durchläuft denselben 4-Knoten-Baum) + # --------------------------------------------------------- + def _start_bots_cycle(self): + for w in self.controls_frame.winfo_children(): + w.destroy() + if not self.bots or not self.engine.any_contender_alive(self.bots): + self._begin_next_turn_cycle() + return + self.active_bot_idx = 0 + self._persist_state() + self._step_next_bot() + + def _step_next_bot(self): + if not self.table_frame.winfo_exists(): + return + + while self.active_bot_idx < len(self.bots): + bot = self.bots[self.active_bot_idx] + if self.engine.bot_needs_turn(bot): + break + self.active_bot_idx += 1 + + if self.active_bot_idx >= len(self.bots): + self.active_bot_idx = -1 + self._persist_state() + self._begin_next_turn_cycle() + return + + bot = self.bots[self.active_bot_idx] + self._persist_state() + self.status_lbl.configure(text=t("bj_bot_turn_status", bot.name)) + self._render_table(reveal_opponents=False, reveal_dealer=False) + self._turn_job = self.ctx.root.after(BJ_BOT_TURN_DELAY_MS, lambda: self._execute_bot_action(bot)) + + def _execute_bot_action(self, bot: BlackjackBotSeat): + if not self.table_frame.winfo_exists(): + return + + upcard = self.engine.dealer_hand[0] + dyn_chips = self._get_current_level_chips() + raw_deficit = max(0, self.engine.highest_bet - bot.bet_in_pot) + to_call = min(bot.gold, raw_deficit) + bot.acted_once = True + + # --- KNOTEN 1: Mitgehen? --- + if not self.bot_ai.decide_step1_mitgehen(bot, self.engine.highest_bet): + if to_call > 0: + bot.folded = True + bot.cards_locked = True + bot.status_text = t("bj_bot_action_fold") + else: + bot.cards_locked = True + bot.status_text = t("bj_bot_action_ready", len(bot.hand)) + self._finish_bot_step() + return + + # Bot geht mit! + if to_call > 0: + self.ctx.sounds.play("click") + self.engine.bot_add_gold_to_pot(bot, to_call) + + # --- KNOTEN 2: Ziehen? --- + drew_card = False + if not bot.cards_locked: + if self.bot_ai.wants_double_down(bot, upcard, self.engine.highest_bet, self.engine.raises_in_round): + dd_cost = max(self.engine.highest_bet, bot.bet_in_pot) * 2 - bot.bet_in_pot + paid = self.engine.bot_add_gold_to_pot(bot, dd_cost) + self.ctx.sounds.play("click") + self.engine.bot_draw_card(bot) + bot.doubled = True + bot.cards_locked = True + + if HandEvaluator.is_triple_seven(bot.hand): + self._trigger_instant_777_win(winner_is_player=False, winning_bot=bot) + return + + if bot.busted: + b_val, _ = HandEvaluator.evaluate(bot.hand) + bot.status_text = t("bj_bot_action_bust", b_val) + else: + bot.status_text = t("bj_bot_action_double", paid) + self._finish_bot_step() + return + + if self.bot_ai.decide_step2_ziehen(bot, upcard, self.engine.deck.remaining()): + self.ctx.sounds.play("click") + self.engine.bot_draw_card(bot) + drew_card = True + + if HandEvaluator.is_triple_seven(bot.hand): + self._trigger_instant_777_win(winner_is_player=False, winning_bot=bot) + return + + # Über 21? -> Verloren! + if bot.busted: + b_val, _ = HandEvaluator.evaluate(bot.hand) + bot.status_text = t("bj_bot_action_bust", b_val) + self._finish_bot_step() + return + + # --- KNOTEN 3: Erhöhen? --- + raise_amt = self.bot_ai.decide_step3_erhoehen( + bot, dyn_chips, self.engine.deck.remaining(), self.engine.raises_in_round + ) + if raise_amt > 0: + self.ctx.sounds.play("click") + self.engine.bot_add_gold_to_pot(bot, raise_amt) + if self.bot_ai.decide_step4_fertig(bot, upcard, self.engine.deck.remaining()): + bot.cards_locked = True + bot.status_text = t("bj_bot_action_bet", raise_amt) + self._finish_bot_step() + return + + # --- KNOTEN 4: Fertig? --- + if self.bot_ai.decide_step4_fertig(bot, upcard, self.engine.deck.remaining()): + bot.cards_locked = True + bot.status_text = ( + t("bj_bot_action_call", to_call) if to_call > 0 else t("bj_bot_action_ready", len(bot.hand)) + ) + else: + bot.status_text = ( + t("bj_bot_action_hit", len(bot.hand)) if drew_card else t("bj_bot_action_check", len(bot.hand)) + ) + + self._finish_bot_step() + + def _finish_bot_step(self): + self.active_bot_idx += 1 + self._persist_state() + self._render_table(reveal_opponents=False, reveal_dealer=False) + self._turn_job = self.ctx.root.after(BJ_BOT_TURN_DELAY_MS, self._step_next_bot) + + # --------------------------------------------------------- + # SHOWDOWN, HAUS-DEALER & ERGEBNIS-POPUP + # --------------------------------------------------------- + def _resolve_devils_lock_after_outcome(self, outcome_type: str): + if not self.devils_locked: + self._clear_persisted_state() + return + + updated_acc = Database.get_blackjack_account(self.bj_account["id"]) + still_only_ten_from_tie = (outcome_type == "TIE" and updated_acc["gold"] == GOLD_MIN_TABLE_ENTRY) + + if not still_only_ten_from_tie: + Database.set_bj_devils_deal_active(self.bj_account["id"], False) + self.devils_locked = False + self._clear_persisted_state() + + def _award_xp_and_record(self, outcome_type: str, won_stat: bool | None) -> tuple[int, int | None]: + duration = max(0.5, time.time() - self.round_start_time) + prog_before = self.ctx.refresh_game_progress() + opp_levels = [b.ai_level for b in self.bots] + + xp_gained = Progression.calculate_match_xp( + player_level=prog_before["level"], + opponent_levels=opp_levels, + outcome_type=outcome_type, + variant_mult=self.cfg["xp_mult"], + ) + + if won_stat is None: + Database.add_game_points(self.ctx.profile["id"], GAME_FOLDER_ID, xp_gained) + prog_after = self.ctx.refresh_game_progress() + self.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 = self.ctx.record_result( + self.variant_key, won=won_stat, duration_sec=duration, + points_gained=xp_gained, bj_account_id=self.bj_account["id"] + ) + return xp_gained, (new_lvl if new_lvl > old_lvl else None) + + def _trigger_instant_777_win(self, winner_is_player: bool, winning_bot: BlackjackBotSeat | None): + self.engine.state = "SHOWDOWN" + self._count_all_table_cards() + pot_total = self.engine.pot + total_p_bet = self.engine.total_player_bet + + if winner_is_player: + payout = pot_total + (total_p_bet if not self.bots else 0) + net = payout - total_p_bet + self.bj_account = Database.update_blackjack_gold(self.bj_account["id"], payout) + xp, leveled_to = self._award_xp_and_record("WIN_777", won_stat=True) + self._resolve_devils_lock_after_outcome("WIN_777") + payload = { + "winner_type": "PLAYER", + "winner_names": [], + "player_won": True, + "player_net": net, + "bank_gain": 0, + "bot_gains": [], + "xp_gained": xp, + "leveled_to": leveled_to, + } + else: + winning_bot.gold += pot_total + bot_net = pot_total - winning_bot.bet_in_pot + xp, leveled_to = self._award_xp_and_record("LOSE", won_stat=False) + self._resolve_devils_lock_after_outcome("LOSE") + payload = { + "winner_type": "BOT", + "winner_names": [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, + } + + self._last_popup_payload = payload + if self.devils_locked: + self._persist_state() + else: + self._build_ui() + self.status_lbl.configure(text="") + self._render_table(reveal_opponents=True, reveal_dealer=True) + self._open_result_popup(self._build_localized_popup_data(payload)) + + def _start_showdown_and_dealer(self): + for w in self.controls_frame.winfo_children(): + w.destroy() + + if not self.engine.any_contender_alive(self.bots): + self._finalize_showdown() + return + + self.engine.state = "DEALER_TURN" + self._persist_state() + self.status_lbl.configure(text=t("bj_dealer_reveals")) + self._render_table(reveal_opponents=True, reveal_dealer=True) + self._turn_job = self.ctx.root.after(BJ_DEALER_DELAY_MS, self._dealer_draw_step) + + def _dealer_draw_step(self): + if not self.table_frame.winfo_exists(): + return + if self.engine.dealer_should_hit(): + self.ctx.sounds.play("click") + self.engine.dealer_hit() + self._persist_state() + self._render_table(reveal_opponents=True, reveal_dealer=True) + self._turn_job = self.ctx.root.after(BJ_DEALER_DELAY_MS, self._dealer_draw_step) + else: + self._finalize_showdown() + + def _count_all_table_cards(self): + if len(self.engine.dealer_hand) >= 2: + for c in self.engine.dealer_hand[1:]: + self.bot_ai.observe_public_card(c) + for h in self.engine.player_hands: + for c in h.cards: + self.bot_ai.observe_public_card(c) + for b in self.bots: + for c in b.hand: + self.bot_ai.observe_public_card(c) + + def _finalize_showdown(self): + self._count_all_table_cards() + res = self.engine.resolve_showdown(self.bots) + + if res["player_payout"] > 0: + self.bj_account = Database.update_blackjack_gold(self.bj_account["id"], res["player_payout"]) + + w_type = res["winner_type"] + if w_type == "PLAYER": + has_natural_bj = any( + h.is_active_in_pot and not h.is_split_hand and HandEvaluator.is_natural_blackjack(h.cards) + for h in self.engine.player_hands + ) + out_code = "WIN_BJ" if has_natural_bj else "WIN" + xp, leveled_to = self._award_xp_and_record(out_code, won_stat=True) + player_won_flag = True + elif w_type == "TIE": + out_code = "TIE" + xp, leveled_to = self._award_xp_and_record("TIE", won_stat=None) + player_won_flag = None + else: + out_code = "LOSE" + xp, leveled_to = self._award_xp_and_record("LOSE", won_stat=False) + player_won_flag = False + + self._resolve_devils_lock_after_outcome(out_code) + + payload = { + "winner_type": w_type, + "winner_names": res["winner_names"], + "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, + } + self._last_popup_payload = payload + if self.devils_locked: + self._persist_state() + else: + self._build_ui() + self.status_lbl.configure(text="") + self._render_table(reveal_opponents=True, reveal_dealer=True) + self._open_result_popup(self._build_localized_popup_data(payload)) + + def _build_localized_popup_data(self, payload: dict) -> dict: + w_type = payload["winner_type"] + if w_type == "BANK": + headline = t("bj_popup_bank_won") + elif w_type == "PLAYER": + headline = t("bj_popup_player_won") + elif w_type == "BOT": + headline = t("bj_popup_bot_won", ", ".join(payload["winner_names"])) + else: + headline = t("bj_popup_tie") + + 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(self.bj_account["id"])["gold"] + can_cont = cur_gold >= GOLD_MIN_TABLE_ENTRY + + 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, + "can_continue": can_cont, + "can_leave_menu": not self.devils_locked, + } + + def _open_result_popup(self, popup_data: dict): + for w in self.controls_frame.winfo_children(): + w.destroy() + + self._result_dialog = BlackjackResultDialog( + parent=self.table_frame, + 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(lambda: self.on_back_to_menu(self.bj_account["id"])), + ) \ No newline at end of file diff --git a/games/blackjack/views/round_result_dialog.py b/games/blackjack/views/round_result_dialog.py new file mode 100644 index 0000000..78b9595 --- /dev/null +++ b/games/blackjack/views/round_result_dialog.py @@ -0,0 +1,131 @@ +# -*- coding: utf-8 -*- +# games/blackjack/views/round_result_dialog.py +import tkinter as tk +from resources.code_res.game_constants import ( + ACCENT_GOLD, ACCENT_GOTH, CELL_BG, ERROR_FG, + FG_COLOR, MODAL_BG, MUTED_FG, SUBTLE_BORDER +) +from resources.code_res.i18n import t +from view.widgets.image_button import ImageButton + + +class BlackjackResultDialog(tk.Frame): + def __init__( + self, + parent, + assets, + sounds, + result_data: dict, + on_next_round, + on_back_to_menu, + ): + super().__init__( + parent, bg=MODAL_BG, padx=32, pady=24, + highlightthickness=2, highlightbackground=ACCENT_GOTH + ) + self.assets = assets + 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.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, 6)) + 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( + self, text=self.data["headline"], + font=("Georgia", 18, "bold"), fg=headline_color, bg=MODAL_BG, + ).pack(pady=(2, 12)) + + info_box = tk.Frame( + self, bg=CELL_BG, padx=22, pady=14, + highlightthickness=1, highlightbackground=SUBTLE_BORDER + ) + info_box.pack(fill="x", pady=(0, 14)) + + p_net = self.data["player_net"] + 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", 12, "bold"), fg=own_col, bg=CELL_BG).pack(pady=3) + + for extra_line in self.data.get("other_gains", []): + tk.Label(info_box, text=extra_line, font=("Helvetica", 11), fg=MUTED_FG, bg=CELL_BG).pack(pady=2) + + tk.Frame(info_box, bg=SUBTLE_BORDER, height=1).pack(fill="x", pady=10) + + tk.Label( + info_box, text=t("bj_popup_xp_earned", self.data["xp_gained"]), + font=("Helvetica", 12, "bold"), fg=ACCENT_GOTH, bg=CELL_BG, + ).pack(pady=2) + + if self.data.get("new_level_title"): + tk.Label( + info_box, text=self.data["new_level_title"], + font=("Georgia", 11, "bold"), fg=ACCENT_GOLD, bg=CELL_BG, + ).pack(pady=(4, 0)) + + btn_row = tk.Frame(self, bg=MODAL_BG) + btn_row.pack(fill="x", pady=(6, 0)) + + if self.data.get("can_continue", True): + ImageButton( + btn_row, t("bj_popup_next_round_btn"), + self.assets.raw_btn, self.assets.raw_btn_active, + self._handle_next, sound_mgr=self.sounds, width=195, height=40, font=("Helvetica", 10, "bold") + ).pack(side="left", padx=(0, 10)) + + if self.data.get("can_leave_menu", True): + ImageButton( + btn_row, t("bj_popup_to_menu_btn"), + self.assets.raw_sel, self.assets.raw_sel_active, + self._handle_menu, sound_mgr=self.sounds, width=165, height=40, font=("Helvetica", 10, "bold") + ).pack(side="right") + + def _start_gif(self, key: str): + 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 + 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() \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..6af97aa --- /dev/null +++ b/main.py @@ -0,0 +1,17 @@ +# -*- coding: utf-8 -*- +from pathlib import Path +from controller.app_controller import AppController +from view.main_window import GothCardCollectionView + + +def main(): + root_path = Path(__file__).resolve().parent + controller = AppController(root_path) + app = GothCardCollectionView(controller, root_path) + controller.bind_view(app) + controller.start() + app.mainloop() + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/models/__pycache__/card.cpython-311.pyc b/models/__pycache__/card.cpython-311.pyc new file mode 100644 index 0000000..983f7ab Binary files /dev/null and b/models/__pycache__/card.cpython-311.pyc differ diff --git a/models/__pycache__/database.cpython-311.pyc b/models/__pycache__/database.cpython-311.pyc new file mode 100644 index 0000000..f27738a Binary files /dev/null and b/models/__pycache__/database.cpython-311.pyc differ diff --git a/models/__pycache__/deck.cpython-311.pyc b/models/__pycache__/deck.cpython-311.pyc new file mode 100644 index 0000000..b7cd975 Binary files /dev/null and b/models/__pycache__/deck.cpython-311.pyc differ diff --git a/models/__pycache__/progression.cpython-311.pyc b/models/__pycache__/progression.cpython-311.pyc new file mode 100644 index 0000000..6a15992 Binary files /dev/null and b/models/__pycache__/progression.cpython-311.pyc differ diff --git a/models/__pycache__/resource_manager.cpython-311.pyc b/models/__pycache__/resource_manager.cpython-311.pyc new file mode 100644 index 0000000..f2c9e8e Binary files /dev/null and b/models/__pycache__/resource_manager.cpython-311.pyc differ diff --git a/models/__pycache__/sound_manager.cpython-311.pyc b/models/__pycache__/sound_manager.cpython-311.pyc new file mode 100644 index 0000000..f4144d5 Binary files /dev/null and b/models/__pycache__/sound_manager.cpython-311.pyc differ diff --git a/models/card.py b/models/card.py new file mode 100644 index 0000000..6e06196 --- /dev/null +++ b/models/card.py @@ -0,0 +1,37 @@ +# -*- coding: utf-8 -*- +from dataclasses import dataclass +from resources.code_res.game_constants import ( + ACE_RANK, CARD_FILE_PATTERN, FACE_RANKS, JOKER_FILES, + JOKER_SUIT, RED_SUITS, SUIT_SYMBOLS +) + + +@dataclass(frozen=True) +class Card: + suit: str + rank: str + + @property + def image_filename(self) -> str: + if self.suit == JOKER_SUIT: + return JOKER_FILES.get(self.rank, JOKER_FILES["1"]) + return CARD_FILE_PATTERN.format(suit=self.suit, rank=self.rank) + + @property + def is_red(self) -> bool: + return self.suit in RED_SUITS + + @property + def blackjack_value(self) -> int: + if self.rank in FACE_RANKS: + return 10 + if self.rank == ACE_RANK: + return 11 + if self.suit == JOKER_SUIT: + return 0 + return int(self.rank) + + def __str__(self) -> str: + if self.suit == JOKER_SUIT: + return JOKER_SUIT.title() + return f"{SUIT_SYMBOLS.get(self.suit, '')}{self.rank}" \ No newline at end of file diff --git a/models/database.py b/models/database.py new file mode 100644 index 0000000..910d2f8 --- /dev/null +++ b/models/database.py @@ -0,0 +1,430 @@ +# -*- coding: utf-8 -*- +# models/database.py +import sqlite3 +from pathlib import Path +import resources.code_res.sql_queries as sql +from resources.code_res.game_constants import ( + BJ_DEFAULT_BET, BJ_STARTING_GOLD, DEVILS_DEAL_GOLD_REWARD, + GOLD_MAX_ACCOUNTS, INTERNAL_DB_REL_PATH, USER_DB_FILENAME, + XP_TO_GOLD_AMOUNT +) + +ROOT_DIR = Path(__file__).resolve().parent.parent +INTERNAL_DB_PATH = ROOT_DIR / INTERNAL_DB_REL_PATH +USER_DB_PATH = ROOT_DIR / USER_DB_FILENAME + + +class Database: + _connection: sqlite3.Connection | None = None + + @classmethod + def conn(cls) -> sqlite3.Connection: + if cls._connection is None: + if not INTERNAL_DB_PATH.is_file(): + raise FileNotFoundError( + f"Interne Stammdaten-DB fehlt: {INTERNAL_DB_PATH}. " + "Bitte zuerst das Seed-SQL mit deinem Query-Executor ausführen!" + ) + c = sqlite3.connect(USER_DB_PATH) + c.row_factory = sqlite3.Row + c.execute(sql.PRAGMA_FOREIGN_KEYS) + c.execute(sql.ATTACH_INTERNAL_DB, (str(INTERNAL_DB_PATH),)) + cls._connection = c + return cls._connection + + @classmethod + def close(cls): + if cls._connection is not None: + cls._connection.close() + cls._connection = None + + @classmethod + def execute(cls, query: str, params: tuple = ()) -> sqlite3.Cursor: + cur = cls.conn().execute(query, params) + cls.conn().commit() + return cur + + @classmethod + def execute_many(cls, query: str, seq_of_params) -> sqlite3.Cursor: + cur = cls.conn().executemany(query, seq_of_params) + cls.conn().commit() + return cur + + @classmethod + def fetch_one(cls, query: str, params: tuple = ()) -> dict | None: + row = cls.conn().execute(query, params).fetchone() + return dict(row) if row else None + + @classmethod + def fetch_all(cls, query: str, params: tuple = ()) -> list[dict]: + return [dict(r) for r in cls.conn().execute(query, params).fetchall()] + + @classmethod + def fetch_val(cls, query: str, params: tuple = (), default=None): + row = cls.conn().execute(query, params).fetchone() + return row[0] if row is not None else default + + @classmethod + def init_db(cls): + cls.conn().executescript(sql.USER_SCHEMA_DDL) + bj_cols = [r["name"] for r in cls.fetch_all(sql.PRAGMA_TABLE_INFO_BJ_ACCOUNTS)] + if "devils_deal_active" not in bj_cols: + cls.conn().execute(sql.MIGRATE_ADD_DEVILS_ACTIVE) + cls.conn().commit() + + @classmethod + def load_all_translations(cls) -> dict[str, dict[str, str]]: + out: dict[str, dict[str, str]] = {"DE": {}, "EN": {}} + for r in cls.fetch_all(sql.SELECT_ALL_I18N): + out.setdefault(r["lang"], {})[r["key"]] = r["val"] + return out + + @classmethod + def load_prestige_ranks(cls) -> list[dict]: + return cls.fetch_all(sql.SELECT_PRESTIGE_RANKS) + + @classmethod + def load_setting(cls, key: str, default: str = "") -> str: + return cls.fetch_val(sql.SELECT_SETTING, (key,), default=default) + + @classmethod + def save_setting(cls, key: str, value: str): + cls.execute(sql.UPSERT_SETTING, (key, str(value))) + + # --- Profile (reiner Account ohne übergreifendes Level!) --- + @classmethod + def get_profiles(cls) -> list[str]: + return [r["name"] for r in cls.fetch_all(sql.SELECT_ALL_PROFILES)] + + @classmethod + def get_or_create_profile(cls, name: str) -> dict: + cls.execute(sql.INSERT_PROFILE_IGNORE, (name,)) + return cls.fetch_one(sql.SELECT_PROFILE_BY_NAME, (name,)) + + @classmethod + def get_profile_by_id(cls, profile_id: int) -> dict | None: + return cls.fetch_one(sql.SELECT_PROFILE_BY_ID, (profile_id,)) + + # --- Spielgebundene Progression (eigenes Level je Spiel!) --- + @classmethod + def get_game_progress(cls, profile_id: int, game_folder: str) -> dict: + from models.progression import Progression + cls.execute(sql.INSERT_GAME_PROGRESS_IGNORE, (profile_id, game_folder)) + row = cls.fetch_one(sql.SELECT_GAME_PROGRESS, (profile_id, game_folder)) + info = Progression.get_level_info( + row["points"], + profile_id=profile_id, + game_folder=game_folder, + ever_deity=bool(row["ever_reached_deity"]), + ) + if info["ever_reached_deity"] and not row["ever_reached_deity"]: + cls.execute(sql.MARK_GAME_EVER_DEITY, (profile_id, game_folder)) + return info + + @classmethod + def get_recorded_game_level_avg_xp(cls, profile_id: int, game_folder: str, level_num: int) -> int: + row = cls.fetch_one(sql.SELECT_GAME_LEVEL_AVG_XP, (profile_id, game_folder, int(level_num))) + if not row or row["games_count"] <= 0: + return 0 + return int(row["total_xp_earned"] // row["games_count"]) + + @classmethod + def _record_game_xp_with_history(cls, profile_id: int, game_folder: str, current_level: int, xp_gained: int): + from models.progression import Progression + if xp_gained <= 0: + return + cls.conn().execute(sql.INSERT_GAME_PROGRESS_IGNORE, (profile_id, game_folder)) + cls.conn().execute(sql.ADD_GAME_POINTS, (int(xp_gained), profile_id, game_folder)) + if current_level >= Progression.get_creator_spirit_v_level(): + cls.conn().execute( + sql.UPSERT_GAME_LEVEL_XP_HISTORY, + (profile_id, game_folder, int(current_level), int(xp_gained)) + ) + + @classmethod + def add_game_points(cls, profile_id: int, game_folder: str, points: int): + if points <= 0: + return + cur_prog = cls.get_game_progress(profile_id, game_folder) + with cls.conn(): + cls._record_game_xp_with_history(profile_id, game_folder, cur_prog["level"], int(points)) + cls.get_game_progress(profile_id, game_folder) + + @classmethod + def adjust_game_points(cls, profile_id: int, game_folder: str, delta_points: int, min_floor_xp: int = 0) -> dict: + """Für künftige Spiel-spezifische Rückstufungen (z.B. Solitaire-Strafen).""" + cur = cls.get_game_progress(profile_id, game_folder) + new_pts = max(min_floor_xp, cur["total_points"] + int(delta_points)) + cls.execute(sql.SET_GAME_POINTS, (new_pts, profile_id, game_folder)) + return cls.get_game_progress(profile_id, game_folder) + + # --- Spielgebundener THE DEVIL'S DEAL (Opfer muss Rang 'Stütze I' IM SELBEN SPIEL haben!) --- + @classmethod + def get_sacrificeable_profiles(cls, active_profile_id: int, game_folder: str) -> list[dict]: + from models.progression import Progression + min_lvl = Progression.get_devils_deal_min_level() + eligible = [] + for row in cls.fetch_all(sql.SELECT_CANDIDATES_FOR_GAME_SACRIFICE, (game_folder, active_profile_id)): + info = Progression.get_level_info(row["points"]) + if info["level"] >= min_lvl: + eligible.append({ + "id": row["id"], + "name": row["name"], + "level": info["level"], + "title": info["title"], + }) + return eligible + + @classmethod + def execute_devils_deal( + cls, active_profile_id: int, game_folder: str, sacrifice_profile_id: int, bj_account_id: int + ) -> tuple[bool, str]: + from resources.code_res.i18n import t + candidates = {c["id"]: c for c in cls.get_sacrificeable_profiles(active_profile_id, game_folder)} + victim = candidates.get(sacrifice_profile_id) + if not victim: + return False, "" + + with cls.conn(): + cls.conn().execute(sql.DELETE_PROFILE_BY_ID, (sacrifice_profile_id,)) + cls.conn().execute(sql.UPDATE_BJ_GOLD_ONLY, (DEVILS_DEAL_GOLD_REWARD, bj_account_id)) + cls.conn().execute(sql.SET_BJ_DEVILS_DEAL_ACTIVE, (1, bj_account_id)) + + acc = cls.get_blackjack_account(bj_account_id) + return True, t("bj_devils_deal_success", victim["name"], DEVILS_DEAL_GOLD_REWARD, acc["account_name"]) + + @classmethod + def get_active_devils_bj_account(cls, profile_id: int) -> dict | None: + return cls.fetch_one(sql.SELECT_ACTIVE_DEVILS_BJ_ACCOUNT, (profile_id,)) + + @classmethod + def set_bj_devils_deal_active(cls, bj_account_id: int, active: bool): + cls.execute(sql.SET_BJ_DEVILS_DEAL_ACTIVE, (1 if active else 0, bj_account_id)) + + # --- Savegames --- + @classmethod + def save_game_state(cls, profile_id: int, game_folder: str, variant_key: str, state_json: str): + cls.execute(sql.UPSERT_SAVEGAME, (profile_id, game_folder, variant_key, state_json)) + + @classmethod + def load_game_state(cls, profile_id: int, game_folder: str) -> dict | None: + return cls.fetch_one(sql.SELECT_SAVEGAME, (profile_id, game_folder)) + + @classmethod + def delete_game_state(cls, profile_id: int, game_folder: str): + cls.execute(sql.DELETE_SAVEGAME, (profile_id, game_folder)) + + # --- Blackjack Gold-Konten & Blackjack-spezifischer XP->Gold-Tausch --- + @classmethod + def get_blackjack_accounts(cls, profile_id: int) -> list[dict]: + return cls.fetch_all(sql.SELECT_BJ_ACCOUNTS_BY_PROFILE, (profile_id,)) + + @classmethod + def get_blackjack_account(cls, bj_account_id: int) -> dict | None: + return cls.fetch_one(sql.SELECT_BJ_ACCOUNT_BY_ID, (bj_account_id,)) + + @classmethod + def create_blackjack_account(cls, profile_id: int, account_name: str) -> dict: + from resources.code_res.i18n import t + clean_name = account_name.strip() + if not clean_name: + raise ValueError(t("bj_err_empty_name")) + if len(cls.get_blackjack_accounts(profile_id)) >= GOLD_MAX_ACCOUNTS: + raise RuntimeError(t("bj_max_acc_reached", GOLD_MAX_ACCOUNTS)) + cls.execute(sql.INSERT_BJ_ACCOUNT, (profile_id, clean_name, BJ_STARTING_GOLD, BJ_DEFAULT_BET)) + return cls.fetch_one(sql.SELECT_BJ_ACCOUNT_BY_NAME, (profile_id, clean_name)) + + @classmethod + def update_blackjack_gold(cls, bj_account_id: int, gold_delta: int, last_bet: int | None = None) -> dict: + if last_bet is not None: + cls.execute(sql.UPDATE_BJ_GOLD_AND_BET, (int(gold_delta), int(last_bet), bj_account_id)) + else: + cls.execute(sql.UPDATE_BJ_GOLD_ONLY, (int(gold_delta), bj_account_id)) + return cls.get_blackjack_account(bj_account_id) + + @classmethod + def save_blackjack_last_bet(cls, bj_account_id: int, bet: int): + cls.execute(sql.UPDATE_BJ_LAST_BET, (int(bet), bj_account_id)) + + @classmethod + def delete_blackjack_account(cls, bj_account_id: int): + cls.execute(sql.DELETE_BJ_ACCOUNT, (bj_account_id,)) + + @classmethod + def exchange_xp_for_bj_gold(cls, profile_id: int, bj_account_id: int) -> tuple[bool, str]: + """Zieht XP AUSSCHLIESSLICH vom Blackjack-Spielfortschritt ('blackjack') ab!""" + from models.progression import Progression + from resources.code_res.i18n import t + + bj_prog = cls.get_game_progress(profile_id, "blackjack") + if bj_prog.get("at_divine_floor"): + return False, t("bj_err_floor_reached") + + cost = bj_prog["xp_exchange_cost"] + is_divine = bj_prog["is_divine_punishment"] + + if not is_divine and bj_prog["total_points"] < cost: + return False, t("bj_err_not_enough_xp", bj_prog["total_points"], cost) + + if is_divine: + floor_xp = Progression.get_creator_spirit_v_floor_xp() + new_points = max(floor_xp, bj_prog["total_points"] - cost) + actual_deducted = bj_prog["total_points"] - new_points + if actual_deducted <= 0: + return False, t("bj_err_floor_reached") + else: + new_points = max(0, bj_prog["total_points"] - cost) + actual_deducted = cost + + with cls.conn(): + cls.conn().execute(sql.SET_GAME_POINTS, (new_points, profile_id, "blackjack")) + cls.conn().execute(sql.UPDATE_BJ_GOLD_ONLY, (XP_TO_GOLD_AMOUNT, bj_account_id)) + cls.conn().execute(sql.SET_BJ_DEVILS_DEAL_ACTIVE, (0, bj_account_id)) + + acc = cls.get_blackjack_account(bj_account_id) + updated_prog = cls.get_game_progress(profile_id, "blackjack") + + if is_divine: + return True, t( + "bj_exchange_divine_success", + XP_TO_GOLD_AMOUNT, acc["account_name"], actual_deducted, updated_prog["title"] + ) + return True, t("bj_exchange_success", XP_TO_GOLD_AMOUNT, acc["account_name"], actual_deducted) + + # --- Bot Configs & Statistiken --- + @classmethod + def load_bot_configs(cls, profile_id: int, game_folder: str) -> dict[int, tuple[str, int]]: + rows = cls.fetch_all(sql.SELECT_BOT_CONFIGS, (profile_id, game_folder)) + return {r["slot_idx"]: (r["bot_name"], r["ai_level"]) for r in rows} + + @classmethod + def save_bot_configs(cls, profile_id: int, game_folder: str, configs: dict[int, tuple[str, int]]): + data = [(profile_id, game_folder, int(idx), name, int(lvl)) for idx, (name, lvl) in configs.items()] + cls.execute_many(sql.UPSERT_BOT_CONFIG, data) + + @classmethod + def _upsert_stat(cls, scope: str, owner_id: int, variant_id: int, won: bool, duration_sec: float): + q = sql.STATS_SQL[scope] + cur = cls.fetch_one(q["select_one"], (owner_id, variant_id)) + dur = max(0.0, duration_sec) + + if not cur: + cls.conn().execute(q["insert"], ( + owner_id, variant_id, + 1 if won else 0, 0 if won else 1, + 1 if won else 0, 1 if won else 0, + dur if won else None, dur, + )) + else: + c_streak = (cur["current_streak"] + 1) if won else 0 + best_t = cur["best_time_sec"] + if won: + best_t = dur if best_t is None else min(best_t, dur) + cls.conn().execute(q["update"], ( + cur["games_played"] + 1, + cur["games_won"] + (1 if won else 0), + cur["games_lost"] + (0 if won else 1), + c_streak, + max(cur["longest_streak"], c_streak), + best_t, + cur["total_time_sec"] + dur, + owner_id, variant_id, + )) + + @classmethod + def record_game_result( + cls, + profile_id: int, + variant_key: str, + won: bool, + duration_sec: float, + points_gained: int = 0, + bj_account_id: int | None = None + ) -> tuple[int, int]: + """Ermittelt aus variant_key automatisch den game_folder und bucht XP nur auf dieses Spiel!""" + var_info = cls.fetch_one(sql.SELECT_VARIANT_INFO_BY_KEY, (variant_key,)) + if not var_info: + raise ValueError(f"Unbekannte Spielvariante in internal_base.db: {variant_key}") + + variant_id = var_info["id"] + game_folder = var_info["folder_path"] + + prog_before = cls.get_game_progress(profile_id, game_folder) + old_lvl = prog_before["level"] + + with cls.conn(): + if points_gained > 0: + cls._record_game_xp_with_history(profile_id, game_folder, old_lvl, int(points_gained)) + cls._upsert_stat("profile", profile_id, variant_id, won, duration_sec) + if bj_account_id is not None: + cls._upsert_stat("bj_account", bj_account_id, variant_id, won, duration_sec) + + new_lvl = cls.get_game_progress(profile_id, game_folder)["level"] + return old_lvl, new_lvl + + @classmethod + def get_variants_for_filter(cls, folder_path: str | None = None) -> list[dict]: + from resources.code_res.i18n import t + rows = ( + cls.fetch_all(sql.SELECT_VARIANTS_BY_FOLDER, (folder_path,)) + if folder_path else cls.fetch_all(sql.SELECT_ALL_VARIANTS) + ) + for d in rows: + d["translated_name"] = t(f"variant_{d['variant_key']}") + return rows + + @classmethod + def _query_stats(cls, scope: str, owner_id: int, variant_id: int | None = None, folder_path: str | None = None) -> dict: + q = sql.STATS_SQL[scope] + if variant_id is not None: + row = cls.fetch_one(q["select_one"], (owner_id, variant_id)) + if not row or row["games_played"] == 0: + return cls._empty_stats() + played, won, lost = row["games_played"], row["games_won"], row["games_lost"] + c_streak, l_streak, best_t, total_t = row["current_streak"], row["longest_streak"], row["best_time_sec"], row["total_time_sec"] + else: + row = ( + cls.fetch_one(q["aggregate_folder"], (owner_id, folder_path)) + if folder_path is not None + else cls.fetch_one(q["aggregate_all"], (owner_id,)) + ) + if not row or row["played"] == 0: + return cls._empty_stats() + played, won, lost = row["played"], row["won"], row["lost"] + c_streak, l_streak, best_t, total_t = row["c_streak"], row["l_streak"], row["best_time"], row["total_time"] + + return { + "played": played, + "won": won, + "lost": lost, + "win_pct": f"{(won / played * 100.0):.1f} %", + "current_streak": c_streak, + "longest_streak": l_streak, + "best_time": cls.format_seconds(best_t), + "avg_time": cls.format_seconds(total_t / played), + } + + @classmethod + def get_stats_overview(cls, profile_id: int, variant_id: int | None = None, folder_path: str | None = None) -> dict: + return cls._query_stats("profile", profile_id, variant_id=variant_id, folder_path=folder_path) + + @classmethod + def get_bj_account_stats_overview(cls, bj_account_id: int, variant_id: int | None = None) -> dict: + return cls._query_stats("bj_account", bj_account_id, variant_id=variant_id, folder_path="blackjack") + + @staticmethod + def format_seconds(sec: float | None) -> str: + if sec is None: + return "--:--" + mins, secs = divmod(int(round(sec)), 60) + if mins >= 60: + hrs, mins = divmod(mins, 60) + return f"{hrs:02d}:{mins:02d}:{secs:02d}" + return f"{mins:02d}:{secs:02d}" + + @staticmethod + def _empty_stats() -> dict: + return { + "played": 0, "won": 0, "lost": 0, "win_pct": "0.0 %", + "current_streak": 0, "longest_streak": 0, "best_time": "--:--", "avg_time": "--:--", + } \ No newline at end of file diff --git a/models/deck.py b/models/deck.py new file mode 100644 index 0000000..c52b5ff --- /dev/null +++ b/models/deck.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- +import random +from models.card import Card +from resources.code_res.game_constants import JOKER_RANKS, JOKER_SUIT, RANKS, SUITS + + +class Deck: + def __init__(self, num_decks: int = 1, include_jokers: bool = False, shuffle_on_init: bool = True): + self.num_decks = max(1, num_decks) + self.include_jokers = include_jokers + self.cards: list[Card] = [] + self.reset(shuffle=shuffle_on_init) + + def reset(self, shuffle: bool = True): + self.cards = [] + for _ in range(self.num_decks): + for s in SUITS: + for r in RANKS: + self.cards.append(Card(s, r)) + if self.include_jokers: + for jr in JOKER_RANKS: + self.cards.append(Card(JOKER_SUIT, jr)) + if shuffle: + self.shuffle() + + def shuffle(self): + random.shuffle(self.cards) + + def draw(self) -> Card: + if not self.cards: + self.reset(shuffle=True) + return self.cards.pop() + + def remaining(self) -> int: + return len(self.cards) \ No newline at end of file diff --git a/models/progression.py b/models/progression.py new file mode 100644 index 0000000..425ce7f --- /dev/null +++ b/models/progression.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# models/progression.py +import resources.code_res.i18n as i18n +from models.database import Database +from resources.code_res.game_constants import ( + DEVILS_DEAL_MIN_RANK_DE, DIVINE_AVG_GAMES_MULT, ROMAN_NUMERALS, + XP_BASE_REQ, XP_EARN_LEVEL_EXPONENT, XP_GROWTH_EXPONENT, XP_TO_GOLD_COST +) + + +class Progression: + _ranks_cache: list[dict] = [] + _creator_v_floor_xp: int | None = None + _support_min_level: int | None = None + + @classmethod + def _get_ranks(cls) -> list[dict]: + if not cls._ranks_cache: + cls._ranks_cache = Database.load_prestige_ranks() + return cls._ranks_cache + + @classmethod + def get_deity_start_level(cls) -> int: + ranks = cls._get_ranks() + tiered_count = max(1, len(ranks) - 1) + return tiered_count * len(ROMAN_NUMERALS) + 1 + + @classmethod + def get_creator_spirit_v_level(cls) -> int: + return cls.get_deity_start_level() - 1 + + @classmethod + def get_creator_spirit_v_floor_xp(cls) -> int: + if cls._creator_v_floor_xp is None: + cv_lvl = cls.get_creator_spirit_v_level() + cls._creator_v_floor_xp = sum(cls.xp_needed_for_level(l) for l in range(1, cv_lvl)) + return cls._creator_v_floor_xp + + @classmethod + def get_devils_deal_min_level(cls) -> int: + if cls._support_min_level is None: + for r in cls._get_ranks(): + if r["title_de"] == DEVILS_DEAL_MIN_RANK_DE: + cls._support_min_level = r["rank_idx"] * len(ROMAN_NUMERALS) + 1 + break + if cls._support_min_level is None: + cls._support_min_level = 421 + return cls._support_min_level + + @staticmethod + def xp_needed_for_level(level: int) -> int: + return int(XP_BASE_REQ * (max(1, int(level)) ** XP_GROWTH_EXPONENT)) + + @classmethod + def estimate_avg_xp_at_level(cls, level: int) -> int: + return cls.calculate_match_xp(level, [3, 4], "WIN", 1.0) + + @classmethod + def get_level_bet_chips(cls, game_level: int, bet_scale: int = 1) -> tuple[int, int, int, int]: + rank_tier = max(1, (max(1, int(game_level)) - 1) // 5 + 1) + base_unit = max(5, rank_tier * 5 * max(1, int(bet_scale))) + return (base_unit, base_unit * 2, base_unit * 5, base_unit * 10) + + @classmethod + def get_xp_exchange_state( + cls, profile_id: int, game_folder: str, total_xp: int, level: int, ever_deity: bool + ) -> dict: + deity_lvl = cls.get_deity_start_level() + floor_xp = cls.get_creator_spirit_v_floor_xp() + + if not ever_deity and level < deity_lvl: + return { + "xp_exchange_cost": XP_TO_GOLD_COST, + "is_divine_punishment": False, + "at_divine_floor": False, + "devils_deal_unlocked": False, + } + + prev_lvl = max(cls.get_creator_spirit_v_level(), level - 1) + avg_prev = Database.get_recorded_game_level_avg_xp(profile_id, game_folder, prev_lvl) + if avg_prev <= 0: + avg_prev = cls.estimate_avg_xp_at_level(prev_lvl) + + target_cost = max(XP_TO_GOLD_COST, int(avg_prev * DIVINE_AVG_GAMES_MULT)) + available_above_floor = max(0, int(total_xp) - floor_xp) + + if level <= cls.get_creator_spirit_v_level() and available_above_floor < XP_TO_GOLD_COST: + return { + "xp_exchange_cost": target_cost, + "is_divine_punishment": True, + "at_divine_floor": True, + "devils_deal_unlocked": True, + } + + effective_cost = min(target_cost, available_above_floor) if available_above_floor > 0 else target_cost + return { + "xp_exchange_cost": effective_cost, + "is_divine_punishment": True, + "at_divine_floor": False, + "devils_deal_unlocked": (level <= cls.get_creator_spirit_v_level()), + } + + @classmethod + def get_level_info( + cls, + total_xp: int, + profile_id: int | None = None, + game_folder: str | None = None, + ever_deity: bool = False, + ) -> dict: + xp = max(0, int(total_xp)) + level = 1 + needed = cls.xp_needed_for_level(level) + remaining = xp + + while remaining >= needed: + remaining -= needed + level += 1 + needed = cls.xp_needed_for_level(level) + + is_now_deity = level >= cls.get_deity_start_level() + ever_flag = bool(ever_deity or is_now_deity) + + state = ( + cls.get_xp_exchange_state(profile_id, game_folder, xp, level, ever_flag) + if (profile_id is not None and game_folder is not None) + else { + "xp_exchange_cost": XP_TO_GOLD_COST, + "is_divine_punishment": ever_flag, + "at_divine_floor": False, + "devils_deal_unlocked": False, + } + ) + + res = { + "game_folder": game_folder or "", + "level": level, + "total_points": xp, + "current_xp": remaining, + "needed_xp": needed, + "title": cls.get_prestige_title(level), + "ever_reached_deity": ever_flag, + } + res.update(state) + return res + + @classmethod + def get_prestige_title(cls, level: int) -> str: + ranks = cls._get_ranks() + if not ranks: + return f"Lv. {level}" + + col = "title_de" if i18n.get_lang() == "DE" else "title_en" + lvl = max(1, int(level)) + tiered_count = len(ranks) - 1 + max_tiered_level = tiered_count * len(ROMAN_NUMERALS) + + if lvl <= max_tiered_level: + r_idx = (lvl - 1) // len(ROMAN_NUMERALS) + rom_idx = (lvl - 1) % len(ROMAN_NUMERALS) + return f"{ranks[r_idx][col]} {ROMAN_NUMERALS[rom_idx]}" + + god_num = lvl - max_tiered_level + return f"{ranks[-1][col]} {god_num}" + + @classmethod + def calculate_match_xp( + cls, + player_level: int, + opponent_levels: list[int], + outcome_type: str, + variant_mult: float = 1.0, + ) -> int: + lvl = max(1, int(player_level)) + lvl_factor = lvl ** XP_EARN_LEVEL_EXPONENT + + if opponent_levels: + avg_opp = sum(o + 1 for o in opponent_levels) / len(opponent_levels) + opp_factor = 1.0 + (avg_opp * 0.16) + (len(opponent_levels) * 0.08) + else: + opp_factor = 0.85 + + base = {"WIN_777": 95.0, "WIN_BJ": 58.0, "WIN": 38.0, "TIE": 12.0, "LOSE": 8.0}.get(outcome_type, 8.0) + return max(2, int(round(base * lvl_factor * opp_factor * variant_mult))) \ No newline at end of file diff --git a/models/resource_manager.py b/models/resource_manager.py new file mode 100644 index 0000000..ad5fd96 --- /dev/null +++ b/models/resource_manager.py @@ -0,0 +1,29 @@ +# -*- coding: utf-8 -*- +from pathlib import Path +from resources.code_res.game_constants import CARD_BACK_PATTERN, DEFAULT_CARD_THEME, UI_IMAGES + + +class ResourceManager: + def __init__(self, root_dir: Path, card_theme: str = DEFAULT_CARD_THEME): + self.root_dir = root_dir + self.res_dir = root_dir / "resources" + self.images_dir = self.res_dir / "images" + self.cards_base_dir = self.images_dir / "cards" + self.sounds_dir = self.res_dir / "sounds" + self.ambiance_dir = self.sounds_dir / "ambiance" + self.menu_effects_dir = self.sounds_dir / "menu_effects" + self.card_theme = card_theme + + @property + def active_cards_dir(self) -> Path: + return self.cards_base_dir / self.card_theme + + def get_card_path(self, filename: str) -> Path: + return self.active_cards_dir / filename + + def get_card_back_path(self, color: str = "Black") -> Path: + return self.active_cards_dir / CARD_BACK_PATTERN.format(color=color) + + def get_ui_image_path(self, key_or_filename: str) -> Path: + filename = UI_IMAGES.get(key_or_filename, key_or_filename) + return self.images_dir / filename \ No newline at end of file diff --git a/models/sound_manager.py b/models/sound_manager.py new file mode 100644 index 0000000..21375ce --- /dev/null +++ b/models/sound_manager.py @@ -0,0 +1,103 @@ +# -*- coding: utf-8 -*- +# models/sound_manager.py +from pathlib import Path +from models.database import Database +from resources.code_res.game_constants import ( + DEFAULT_VOL_AMBIANCE, DEFAULT_VOL_MENU, + INGAME_MUSIC_FILE, MENU_MUSIC_FILE, SOUND_MAP +) + +try: + import pygame + PYGAME_AVAILABLE = True +except ImportError: + PYGAME_AVAILABLE = False + + +class SoundManager: + def __init__(self, sounds_dir: Path): + self.ambiance_dir = sounds_dir / "ambiance" + self.menu_dir = sounds_dir / "menu_effects" + + self.ambiance_volume = self._clamp(float(Database.load_setting("vol_ambiance", str(DEFAULT_VOL_AMBIANCE)))) + self.menu_volume = self._clamp(float(Database.load_setting("vol_menu", str(DEFAULT_VOL_MENU)))) + + self._sfx_cache = {} + self._current_music_file = None + self._ready = False + + if PYGAME_AVAILABLE: + try: + pygame.mixer.init(frequency=44100, size=-16, channels=2, buffer=512) + self._ready = True + except Exception: + self._ready = False + + @staticmethod + def _clamp(val: float) -> float: + return max(0.0, min(1.0, val)) + + def set_ambiance_volume(self, volume: float, persist: bool = True): + self.ambiance_volume = self._clamp(volume) + if self._ready: + try: + pygame.mixer.music.set_volume(self.ambiance_volume) + except Exception: + pass + if persist: + Database.save_setting("vol_ambiance", f"{self.ambiance_volume:.3f}") + + def set_menu_volume(self, volume: float, persist: bool = True): + self.menu_volume = self._clamp(volume) + if persist: + Database.save_setting("vol_menu", f"{self.menu_volume:.3f}") + + def play_menu_music(self): + self._switch_music(MENU_MUSIC_FILE) + + def play_ingame_music(self): + self._switch_music(INGAME_MUSIC_FILE) + + def _switch_music(self, filename: str): + if not self._ready: + return + if self._current_music_file == filename and pygame.mixer.music.get_busy(): + pygame.mixer.music.set_volume(self.ambiance_volume) + return + + track_path = self.ambiance_dir / filename + if not track_path.is_file(): + return + + try: + if pygame.mixer.music.get_busy(): + pygame.mixer.music.fadeout(250) + pygame.mixer.music.load(str(track_path)) + pygame.mixer.music.set_volume(self.ambiance_volume) + pygame.mixer.music.play(-1, fade_ms=400) + self._current_music_file = filename + except Exception: + pass + + def play(self, event_name: str): + if not self._ready or event_name not in SOUND_MAP: + return + + category, filename = SOUND_MAP[event_name] + vol = self.ambiance_volume if category == "ambiance" else self.menu_volume + if vol <= 0.001: + return + + if event_name not in self._sfx_cache: + base_folder = self.ambiance_dir if category == "ambiance" else self.menu_dir + fpath = base_folder / filename + if fpath.is_file(): + try: + self._sfx_cache[event_name] = pygame.mixer.Sound(str(fpath)) + except Exception: + return + + snd = self._sfx_cache.get(event_name) + if snd: + snd.set_volume(vol) + snd.play() \ No newline at end of file diff --git a/resources/code_res/__init__.py b/resources/code_res/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/resources/code_res/__pycache__/__init__.cpython-311.pyc b/resources/code_res/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..36268c2 Binary files /dev/null and b/resources/code_res/__pycache__/__init__.cpython-311.pyc differ diff --git a/resources/code_res/__pycache__/game_constants.cpython-311.pyc b/resources/code_res/__pycache__/game_constants.cpython-311.pyc new file mode 100644 index 0000000..4aa830b Binary files /dev/null and b/resources/code_res/__pycache__/game_constants.cpython-311.pyc differ diff --git a/resources/code_res/__pycache__/i18n.cpython-311.pyc b/resources/code_res/__pycache__/i18n.cpython-311.pyc new file mode 100644 index 0000000..e5af8dd Binary files /dev/null and b/resources/code_res/__pycache__/i18n.cpython-311.pyc differ diff --git a/resources/code_res/__pycache__/sql_queries.cpython-311.pyc b/resources/code_res/__pycache__/sql_queries.cpython-311.pyc new file mode 100644 index 0000000..70112f2 Binary files /dev/null and b/resources/code_res/__pycache__/sql_queries.cpython-311.pyc differ diff --git a/resources/code_res/add_gambit.sql b/resources/code_res/add_gambit.sql new file mode 100644 index 0000000..8dead08 --- /dev/null +++ b/resources/code_res/add_gambit.sql @@ -0,0 +1,16 @@ +BEGIN TRANSACTION; + +INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES +('bj_no_account_item', 'DE', '— Noch kein Konto angelegt —'), +('bj_gold_display_lbl', 'DE', 'Aktuelles Guthaben: {0} Gold'), +('bj_gold_display_none', 'DE', 'Aktuelles Guthaben: — (Bitte erst ein Konto anlegen)'), +('bj_stats_view_topbar', 'DE', 'Blackjack – Konto-Statistiken'), +('bj_stats_select_acc_lbl', 'DE', 'Goldbeutel auswählen:'), + +('bj_no_account_item', 'EN', '— No account created yet —'), +('bj_gold_display_lbl', 'EN', 'Current Balance: {0} Gold'), +('bj_gold_display_none', 'EN', 'Current Balance: — (Create an account first)'), +('bj_stats_view_topbar', 'EN', 'Blackjack – Account Statistics'), +('bj_stats_select_acc_lbl', 'EN', 'Select Gold Pouch:'); + +COMMIT; \ No newline at end of file diff --git a/resources/code_res/game_constants.py b/resources/code_res/game_constants.py new file mode 100644 index 0000000..77d5445 --- /dev/null +++ b/resources/code_res/game_constants.py @@ -0,0 +1,179 @@ +# -*- coding: utf-8 -*- +# resources/code_res/game_constants.py + +# --- Dateien & Verzeichnisse --- +INTERNAL_DB_REL_PATH = "resources/code_res/internal_base.db" +USER_DB_FILENAME = "user_data.db" +GAMES_ROOT_DIR = "games" +ENTRY_FILENAME = "start.py" +DEFAULT_CARD_THEME = "default" + +UI_IMAGES = { + "background": "background.jpeg", + "title": "title1.png", + "btn_normal": "button1.png", + "btn_active": "button1_active.png", + "sel_inactive": "selection_inactive.png", + "sel_active": "selection_active.png", + "card_frame": "chat_window.png", + "win_gif": "win.gif", + "lose_gif": "lose.gif", +} + +# --- Flache Hauptkategorien (niemals Unterkategorien!) --- +CAT_LUCK = "luck" +CAT_SOLO = "solo" +CAT_PARTY_OFFLINE = "party_offline" +CAT_ONLINE = "online" + +GAME_CATEGORIES = ( + (CAT_LUCK, "cat_luck", "cat_desc_luck"), + (CAT_SOLO, "cat_solo", "cat_desc_solo"), + (CAT_PARTY_OFFLINE, "cat_party_offline", "cat_desc_party_offline"), + (CAT_ONLINE, "cat_online", "cat_desc_online"), +) + +# --- Dynamischer Game-Loader & Kategorie-Zuordnung --- +GAME_FOLDERS = ( + "blackjack", + "poker", + "solitaire/freecell", + "solitaire/klondike", + "solitaire/spider_solitaire", +) + +FOLDER_CATEGORY_MAP = { + "blackjack": CAT_LUCK, + "poker": CAT_LUCK, + "solitaire/freecell": CAT_SOLO, + "solitaire/klondike": CAT_SOLO, + "solitaire/spider_solitaire": CAT_SOLO, +} + +STAT_GAME_GROUPS = ( + ("blackjack", "game_title_blackjack"), + ("poker", "game_title_poker"), + ("solitaire/klondike", "game_title_klondike"), + ("solitaire/freecell", "game_title_freecell"), + ("solitaire/spider_solitaire", "game_title_spider_solitaire"), +) + +# --- Karten-Definitionen --- +SUITS = ("C", "D", "H", "S") +RED_SUITS = ("D", "H") +RANKS = ("2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A") +FACE_RANKS = ("J", "Q", "K") +ACE_RANK = "A" +SEVEN_RANK = "7" +JOKER_SUIT = "JOKER" +JOKER_RANKS = ("1", "2") + +SUIT_SYMBOLS = { + "C": "♣", + "D": "♦", + "H": "♥", + "S": "♠", + "JOKER": "★", +} + +CARD_FILE_PATTERN = "{suit}{rank}.png" +CARD_BACK_PATTERN = "Back_{color}.png" +JOKER_FILES = { + "1": "Joker.png", + "2": "Joker2.png", +} + +# --- Audio & Sound-Zuordnung --- +MENU_MUSIC_FILE = "Beyond_The_Iron_Gate.mp3" +INGAME_MUSIC_FILE = "The_Midnight_Hand.mp3" +DEFAULT_VOL_AMBIANCE = 0.35 +DEFAULT_VOL_MENU = 0.70 + +SOUND_MAP = { + "click": ("menu", "click.ogg"), + "deal": ("menu", "roll-for-initiative.mp3"), + "win": ("menu", "success.mp3"), + "lose": ("menu", "failure.mp3"), + "end_battle": ("menu", "end-battle.mp3"), + "stand": ("ambiance", "owl-city-stand-sfx.mp3"), +} + +# --- Progression, Divine Punishment & The Devil's Deal --- +ROMAN_NUMERALS = ("I", "II", "III", "IV", "V") +XP_BASE_REQ = 100 +XP_GROWTH_EXPONENT = 1.68 +XP_EARN_LEVEL_EXPONENT = 0.55 + +GOLD_MAX_ACCOUNTS = 5 +GOLD_MIN_TABLE_ENTRY = 10 +XP_TO_GOLD_COST = 10000 +XP_TO_GOLD_AMOUNT = 10 + +DIVINE_AVG_GAMES_MULT = 10 +DEVILS_DEAL_MIN_RANK_DE = "Stütze" +DEVILS_DEAL_GOLD_REWARD = 10 + +STAT_FIELD_KEYS = ( + ("played", "stat_played"), + ("won", "stat_won"), + ("lost", "stat_lost"), + ("win_pct", "stat_win_pct"), + ("current_streak", "stat_current_streak"), + ("longest_streak", "stat_longest_streak"), + ("best_time", "stat_best_time"), + ("avg_time", "stat_avg_time"), +) + +# --- Bots (0..5 Offline-Stufen, 6 = Gottheit / Online-Standard!) --- +BOT_DEITY_LEVEL = 6 +BOT_LEVEL_COUNT = 7 +BJ_MAX_BOTS = 3 +BJ_STARTING_GOLD = 1000 +BJ_INITIAL_ANTE = 10 +BJ_DEFAULT_BET = 10 +BJ_TARGET_SCORE = 21 +BJ_DEALER_STAND = 17 +BJ_MAX_RAISES_PER_ROUND = 4 +BJ_RESHUFFLE_RATIO = 0.20 +BJ_BOT_TURN_DELAY_MS = 550 +BJ_DEALER_DELAY_MS = 650 + +BJ_VARIANTS = { + "bj_classic": { + "decks": 2, + "min_bet": BJ_INITIAL_ANTE, + "bet_scale": 1, + "xp_mult": 1.0, + "back_color": "Black", + }, + "bj_highstakes": { + "decks": 6, + "min_bet": BJ_INITIAL_ANTE, + "bet_scale": 2, + "xp_mult": 1.45, + "back_color": "Red", + }, +} + +# --- UI Theme & Geometrie --- +DEFAULT_WINDOW_GEOM = "1150x800" +MIN_WINDOW_SIZE = (980, 700) +MENU_CARD_SIZE = (185, 245) +PLAYING_CARD_SIZE = (102, 148) +BJ_SPLIT_CARD_SIZE = (84, 122) +BJ_BOT_CARD_SIZE = (64, 94) +OUTCOME_GIF_SIZE = (170, 95) + +BG_COLOR = "#0d0b12" +PANEL_BG = "#1b1821" +CELL_BG = "#24202c" +TABLE_BG = "#17141d" +MODAL_BG = "#0b090e" +INPUT_BG = "#1e1b24" +BORDER_COLOR = "#4a3f5c" +SUBTLE_BORDER = "#362f42" +FG_COLOR = "#e6e1ec" +MUTED_FG = "#aaa2b8" +ERROR_FG = "#ff7b7b" +ACCENT_GOTH = "#b388eb" +ACCENT_GOLD = "#d4af37" \ No newline at end of file diff --git a/resources/code_res/i18n.py b/resources/code_res/i18n.py new file mode 100644 index 0000000..388e2fb --- /dev/null +++ b/resources/code_res/i18n.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# resources/code_res/i18n.py +from models.database import Database, INTERNAL_DB_PATH + +SUPPORTED_LANGS = ("DE", "EN") +CURRENT_LANG = "DE" +_CACHE: dict[str, dict[str, str]] = {} +_MISSING_WARNED: set[str] = set() + + +def reload_translations(): + global _CACHE + _CACHE = Database.load_all_translations() + + +def set_lang(lang_code: str): + global CURRENT_LANG + code = (lang_code or "DE").upper() + CURRENT_LANG = code if code in SUPPORTED_LANGS else "DE" + + +def get_lang() -> str: + return CURRENT_LANG + + +def next_lang() -> str: + idx = SUPPORTED_LANGS.index(CURRENT_LANG) + new_lang = SUPPORTED_LANGS[(idx + 1) % len(SUPPORTED_LANGS)] + set_lang(new_lang) + return new_lang + + +def t(key: str, *args) -> str: + if not _CACHE: + reload_translations() + + lang_dict = _CACHE.get(CURRENT_LANG, {}) + raw = lang_dict.get(key) or _CACHE.get("DE", {}).get(key) + + if raw is None: + if key not in _MISSING_WARNED: + _MISSING_WARNED.add(key) + print(f"[i18n FEHLT] Key '{key}' nicht in {INTERNAL_DB_PATH} gefunden!") + return f"{key}: {' | '.join(str(a) for a in args)}" if args else key + + text = raw.replace("\\n", "\n") + try: + return text.format(*args) if args else text + except Exception: + return text \ No newline at end of file diff --git a/resources/code_res/internal_base.db b/resources/code_res/internal_base.db new file mode 100644 index 0000000..de5c8f4 Binary files /dev/null and b/resources/code_res/internal_base.db differ diff --git a/resources/code_res/internal_base.sql b/resources/code_res/internal_base.sql new file mode 100644 index 0000000..49f615f --- /dev/null +++ b/resources/code_res/internal_base.sql @@ -0,0 +1,743 @@ +PRAGMA foreign_keys = ON; +BEGIN TRANSACTION; + +DROP TABLE IF EXISTS base_i18n; +DROP TABLE IF EXISTS base_prestige_ranks; +DROP TABLE IF EXISTS game_variants; + +-- ========================================================================= +-- 1. STAMMDATEN-TABELLEN +-- ========================================================================= + +CREATE TABLE base_i18n ( + key TEXT NOT NULL, + lang TEXT NOT NULL, + val TEXT NOT NULL, + PRIMARY KEY (key, lang) +); + +CREATE TABLE base_prestige_ranks ( + rank_idx INTEGER PRIMARY KEY, + title_de TEXT NOT NULL, + title_en TEXT NOT NULL +); + +CREATE TABLE game_variants ( + id INTEGER PRIMARY KEY, + folder_path TEXT NOT NULL, + game_name TEXT NOT NULL, + variant_key TEXT UNIQUE NOT NULL, + display_name TEXT NOT NULL +); + +-- ========================================================================= +-- 2. FESTE SPIELVARIANTEN +-- ========================================================================= + +INSERT INTO game_variants (id, folder_path, game_name, variant_key, display_name) VALUES +(101, 'blackjack', 'Blackjack', 'bj_classic', 'Blackjack - Classic'), +(102, 'blackjack', 'Blackjack', 'bj_highstakes', 'Blackjack - High Stakes'), +(201, 'poker', 'Poker', 'poker_holdem', 'Texas Hold''em - Classic'), +(202, 'poker', 'Poker', 'poker_holdem_high', 'Texas Hold''em - High Stakes'), +(301, 'solitaire/klondike', 'Klondike', 'klondike_1', 'Klondike - Draw 1'), +(302, 'solitaire/klondike', 'Klondike', 'klondike_3', 'Klondike - Draw 3'), +(401, 'solitaire/freecell', 'FreeCell', 'freecell_std', 'FreeCell - Standard'), +(501, 'solitaire/spider_solitaire', 'Spider Solitaire', 'spider_1suit', 'Spider - 1 Suit'), +(502, 'solitaire/spider_solitaire', 'Spider Solitaire', 'spider_2suit', 'Spider - 2 Suits'), +(503, 'solitaire/spider_solitaire', 'Spider Solitaire', 'spider_4suit', 'Spider - 4 Suits'); + +-- ========================================================================= +-- 3. ALLE PRESTIGE-RÄNGE (0..258 in I-V, 259 = Gottheit 1, 2, 3...) +-- ========================================================================= + +INSERT INTO base_prestige_ranks (rank_idx, title_de, title_en) VALUES +(0, 'Erst-Starter', 'First-Starter'), +(1, 'Küken', 'Hatchling'), +(2, 'Frischling', 'Fledgling'), +(3, 'Grünschnabel', 'Greenhorn'), +(4, 'Ahnungsloser', 'Clueless'), +(5, 'Zuschauer', 'Spectator'), +(6, 'Zaungast', 'Bystander'), +(7, 'Mitläufer', 'Follower'), +(8, 'Stolperer', 'Stumbler'), +(9, 'Tapsiger', 'Fumbler'), +(10, 'Schnupperer', 'Dabbler'), +(11, 'Probierer', 'Taster'), +(12, 'Neugieriger', 'Curious'), +(13, 'Sucher', 'Seeker'), +(14, 'Tastender', 'Feeler'), +(15, 'Lerner', 'Learner'), +(16, 'Anfänger', 'Beginner'), +(17, 'Neuling', 'Newcomer'), +(18, 'Einsteiger', 'Entrant'), +(19, 'Debütant', 'Debutant'), +(20, 'Auszubildender', 'Trainee'), +(21, 'Praktikant', 'Intern'), +(22, 'Lehrling', 'Apprentice'), +(23, 'Schüler', 'Pupil'), +(24, 'Jungspund', 'Youngster'), +(25, 'Zögling', 'Protege'), +(26, 'Anwärter', 'Candidate'), +(27, 'Aspirant', 'Aspirant'), +(28, 'Novize', 'Novice'), +(29, 'Initiand', 'Initiate'), +(30, 'Hilfskraft', 'Helper'), +(31, 'Handlanger', 'Henchman'), +(32, 'Zuarbeiter', 'Assistant'), +(33, 'Gehilfe', 'Aide'), +(34, 'Knappe', 'Squire'), +(35, 'Läufer', 'Runner'), +(36, 'Späher', 'Scout'), +(37, 'Kundschafter', 'Pathfinder'), +(38, 'Rekrut', 'Recruit'), +(39, 'Kadett', 'Cadet'), +(40, 'Aufsteiger', 'Riser'), +(41, 'Fortgeschrittener', 'Intermediate'), +(42, 'Geübter', 'Practiced'), +(43, 'Erprobter', 'Tested'), +(44, 'Bewährter', 'Proven'), +(45, 'Tauglicher', 'Capable'), +(46, 'Fähiger', 'Able'), +(47, 'Geschickter', 'Skillful'), +(48, 'Gewandter', 'Adroit'), +(49, 'Behender', 'Nimble'), +(50, 'Geselle', 'Journeyman'), +(51, 'Handwerker', 'Craftsman'), +(52, 'Schaffender', 'Creator'), +(53, 'Macher', 'Maker'), +(54, 'Praktiker', 'Practitioner'), +(55, 'Anwender', 'Applier'), +(56, 'Umsetzer', 'Implementer'), +(57, 'Ausführender', 'Executor'), +(58, 'Routinier', 'Regular'), +(59, 'Stammkraft', 'Mainstay'), +(60, 'Kenner', 'Connoisseur'), +(61, 'Wissender', 'Knower'), +(62, 'Kundiger', 'Versed'), +(63, 'Belesener', 'Erudite'), +(64, 'Gelehrter', 'Scholar'), +(65, 'Denker', 'Thinker'), +(66, 'Planer', 'Planner'), +(67, 'Rechner', 'Calculator'), +(68, 'Prüfer', 'Examiner'), +(69, 'Analytiker', 'Analyst'), +(70, 'Könner', 'Adept'), +(71, 'Fachkraft', 'Skilled Pro'), +(72, 'Fachmann', 'Professionalist'), +(73, 'Sachverständiger', 'Surveyor'), +(74, 'Berater', 'Advisor'), +(75, 'Spezialist', 'Specialist'), +(76, 'Techniker', 'Technician'), +(77, 'Methodiker', 'Methodist'), +(78, 'Systematiker', 'Systematist'), +(79, 'Präzisionsarbeiter', 'Precisionist'), +(80, 'Profi', 'Pro'), +(81, 'Berufsspieler', 'Pro Gambler'), +(82, 'Vollprofi', 'Full Pro'), +(83, 'Leistungsträger', 'Key Player'), +(84, 'Stütze', 'Support'), +(85, 'Säule', 'Pillar'), +(86, 'Garant', 'Guarantor'), +(87, 'Fels', 'Rock'), +(88, 'Anker', 'Anchor'), +(89, 'Rückgrat', 'Backbone'), +(90, 'Taktiker', 'Tactician'), +(91, 'Stratege', 'Strategist'), +(92, 'Fuchs', 'Fox'), +(93, 'Schlitzohr', 'Sharpster'), +(94, 'Stratege der Tiefe', 'Deep Strategist'), +(95, 'Drahtzieher', 'Mastermind'), +(96, 'Lenker', 'Steersman'), +(97, 'Leiter', 'Director'), +(98, 'Koordinator', 'Coordinator'), +(99, 'Regisseur', 'Conductor'), +(100, 'Experte', 'Expert'), +(101, 'Koryphäe', 'Luminary'), +(102, 'Kapazität', 'Capacity'), +(103, 'Autorität', 'Authority'), +(104, 'Instanz', 'Instance'), +(105, 'Referenz', 'Reference'), +(106, 'Maßstab', 'Benchmark'), +(107, 'Vorbild', 'Role Model'), +(108, 'Wegweiser', 'Guidepost'), +(109, 'Pionier', 'Pioneer'), +(110, 'Veteran', 'Veteran'), +(111, 'Altgedienter', 'Old Hand'), +(112, 'Haudegen', 'Warhorse'), +(113, 'Schlachtross', 'Battle Charger'), +(114, 'Überlebender', 'Survivor'), +(115, 'Abgehärteter', 'Hardened'), +(116, 'Unerschütterlicher', 'Unshakable'), +(117, 'Standhafter', 'Steadfast'), +(118, 'Eiserner', 'Ironclad'), +(119, 'Unbeugsamer', 'Indomitable'), +(120, 'Meister', 'Master'), +(121, 'Lehrmeister', 'Grand Tutor'), +(122, 'Zuchtmeister', 'Taskmaster'), +(123, 'Schulmeister', 'Schoolmaster'), +(124, 'Werkmeister', 'Guild Craftsman'), +(125, 'Gildenmeister', 'Guildmaster'), +(126, 'Ordensmeister', 'Order Master'), +(127, 'Logenmeister', 'Lodge Master'), +(128, 'Ratsmeister', 'Council Master'), +(129, 'Ehrenmeister', 'Honorary Master'), +(130, 'Virtuose', 'Virtuoso'), +(131, 'Künstler', 'Artist'), +(132, 'Feingeist', 'Refined Spirit'), +(133, 'Ästhet', 'Aesthete'), +(134, 'Perfektionist', 'Perfectionist'), +(135, 'Vollender', 'Completer'), +(136, 'Meisterhand', 'Master Hand'), +(137, 'Wunderkind', 'Prodigy'), +(138, 'Ausnahmetalent', 'Exceptional Talent'), +(139, 'Jahrhunderttalent', 'Century Talent'), +(140, 'Elite', 'Elite'), +(141, 'Auserwählter', 'Chosen'), +(142, 'Berufener', 'Destined'), +(143, 'Herausragender', 'Preeminent'), +(144, 'Überlegener', 'Superior'), +(145, 'Spitzenreiter', 'Frontrunner'), +(146, 'Vorreiter', 'Trailblazer'), +(147, 'Anführer', 'Leader'), +(148, 'Kommandant', 'Commander'), +(149, 'Feldherr', 'Warlord'), +(150, 'Großmeister', 'Grandmaster'), +(151, 'Erzmeister', 'Archmaster'), +(152, 'Hochmeister', 'High Master'), +(153, 'Oberhaupt', 'Chief'), +(154, 'Patriarch', 'Patriarch'), +(155, 'Doyen', 'Doyen'), +(156, 'Altmeister', 'Old Master'), +(157, 'Übermeister', 'Overmaster'), +(158, 'Großstratege', 'Grand Strategist'), +(159, 'Meisterdenker', 'Master Thinker'), +(160, 'Champion', 'Champion'), +(161, 'Titelträger', 'Titleholder'), +(162, 'Sieger', 'Victor'), +(163, 'Triumphator', 'Triumphator'), +(164, 'Gewinner', 'Winner'), +(165, 'Überwinder', 'Overcomer'), +(166, 'Bezwinger', 'Vanquisher'), +(167, 'Eroberer', 'Conqueror'), +(168, 'Unterwerfer', 'Subjugator'), +(169, 'Herrscher', 'Ruler'), +(170, 'Held', 'Hero'), +(171, 'Volksheld', 'Folk Hero'), +(172, 'Retter', 'Savior'), +(173, 'Beschützer', 'Protector'), +(174, 'Wächter', 'Guardian'), +(175, 'Hüter', 'Keeper'), +(176, 'Schildträger', 'Shieldbearer'), +(177, 'Schwertträger', 'Swordbearer'), +(178, 'Bannerträger', 'Bannerbearer'), +(179, 'Lichtbringer', 'Lightbringer'), +(180, 'Ikone', 'Icon'), +(181, 'Idol', 'Idol'), +(182, 'Vorzeigefigur', 'Figurehead'), +(183, 'Ruhmesträger', 'Glorybearer'), +(184, 'Ehrenträger', 'Honorbearer'), +(185, 'Würdenträger', 'Dignitary'), +(186, 'Gekröntes Haupt', 'Crowned Head'), +(187, 'Hoheit', 'Highness'), +(188, 'Majestät', 'Majesty'), +(189, 'Souverän', 'Sovereign'), +(190, 'Legende', 'Legend'), +(191, 'Lebende Legende', 'Living Legend'), +(192, 'Unvergessener', 'Unforgotten'), +(193, 'Verewigter', 'Immortalized'), +(194, 'Ruhmreicher', 'Glorious'), +(195, 'Glorreicher', 'Illustrious'), +(196, 'Strahlender', 'Radiant'), +(197, 'Erleuchteter', 'Enlightened'), +(198, 'Weiser', 'Sage'), +(199, 'Orakel', 'Oracle'), +(200, 'Mythos', 'Myth'), +(201, 'Fabelwesen', 'Mythic Being'), +(202, 'Sagenfigur', 'Fabled Figure'), +(203, 'Phantom', 'Phantom'), +(204, 'Schattenläufer', 'Shadowwalker'), +(205, 'Schicksalsweber', 'Fateweaver'), +(206, 'Weltenwanderer', 'Worldwalker'), +(207, 'Zeitloser', 'Timeless'), +(208, 'Ewiger', 'Eternal'), +(209, 'Unendlicher', 'Infinite'), +(210, 'Unbesiegbarer', 'Invincible'), +(211, 'Unbezwingbarer', 'Unconquerable'), +(212, 'Unantastbarer', 'Untouchable'), +(213, 'Unfehlbarer', 'Infallible'), +(214, 'Allwissender', 'Omniscient'), +(215, 'Allsehender', 'All-Seeing'), +(216, 'Allmächtiger', 'Almighty'), +(217, 'Schöpfer', 'Maker of Realms'), +(218, 'Weltenformer', 'Worldshaper'), +(219, 'Kosmoswächter', 'Cosmos Warden'), +(220, 'Titan', 'Titan'), +(221, 'Gigant', 'Giant'), +(222, 'Koloss', 'Colossus'), +(223, 'Urgewalt', 'Primal Force'), +(224, 'Naturgewalt', 'Force of Nature'), +(225, 'Sturmbringer', 'Stormbringer'), +(226, 'Weltenbrecher', 'Worldbreaker'), +(227, 'Sternengucker', 'Stargazer'), +(228, 'Sternenwanderer', 'Starwalker'), +(229, 'Sternenschmied', 'Starforger'), +(230, 'Halbgott', 'Demigod'), +(231, 'Götterbote', 'Herald of Gods'), +(232, 'Götterliebling', 'Gods'' Favored'), +(233, 'Göttergleicher', 'Godlike'), +(234, 'Himmelsstürmer', 'Skybreaker'), +(235, 'Sphärenwandler', 'Spherewalker'), +(236, 'Ätherweber', 'Aetherweaver'), +(237, 'Astralreisender', 'Astral Traveler'), +(238, 'Lichtgestalt', 'Light Being'), +(239, 'Transzendenter', 'Transcendent'), +(240, 'Unsterblicher', 'Immortal'), +(241, 'Erhabener', 'Exalted'), +(242, 'Geweihter', 'Consecrated'), +(243, 'Gesegneter', 'Blessed'), +(244, 'Heiliger', 'Saint'), +(245, 'Prophet', 'Prophet'), +(246, 'Erlöser', 'Redeemer'), +(247, 'Avatar', 'Avatar'), +(248, 'Inkarnation', 'Incarnation'), +(249, 'Manifestation', 'Manifestation'), +(250, 'Ursprung', 'Origin'), +(251, 'Anfang und Ende', 'Beginning and End'), +(252, 'Alpha', 'Alpha'), +(253, 'Omega', 'Omega'), +(254, 'Paradoxon', 'Paradox'), +(255, 'Singularität', 'Singularity'), +(256, 'Absolutum', 'Absolute'), +(257, 'Übergott', 'Overgod'), +(258, 'Schöpfergeist', 'Creator Spirit'), +(259, 'Gottheit', 'Deity'); + +-- ========================================================================= +-- 4. ALLE ÜBERSETZUNGEN (DE) +-- ========================================================================= + +INSERT INTO base_i18n (key, lang, val) VALUES +-- Global & Navigation +('app_title', 'DE', 'The Goth Cardgame Collection'), +('header_title', 'DE', 'GOTH CARD COLLECTION'), +('btn_audio', 'DE', 'Audio'), +('btn_lang', 'DE', 'Sprache: DE'), +('btn_stats', 'DE', 'Statistiken'), +('btn_back_main', 'DE', '← Hauptmenü'), +('btn_back_game_menu', 'DE', '← Spielmenü'), +('btn_switch_profile', 'DE', '← Profil wechseln'), +('level_badge', 'DE', '{0} • {1} (Lv. {2} | {3}/{4} XP)'), +('main_acc_header', 'DE', '{0} • {1} (Lv. {2} | {3} XP)'), +('main_acc_soul_only', 'DE', 'Seele: {0}'), +('menu_card_rank_sub', 'DE', '{0}' || char(10) || 'Lv. {1}'), +('xp_next_level', 'DE', '{0} / {1} XP bis Lv. {2}'), + +-- Login +('login_select_lbl', 'DE', 'Vorhandenes Profil wählen:'), +('login_create_lbl', 'DE', 'Neues Seelen-Profil anlegen:'), +('login_btn', 'DE', 'Anmelden'), +('new_profile_btn', 'DE', 'Neuer Account'), + +-- Hauptmenü, 4 Hauptkategorien & Spiel-Statistik +('choose_cardgame', 'DE', 'Wähle ein Kartenspiel'), +('no_games_found', 'DE', 'Noch keine start.py im Ordner games/ gefunden.'), +('cat_luck', 'DE', 'Glück'), +('cat_solo', 'DE', 'Solo'), +('cat_party_offline', 'DE', 'Gesellschaft - Offline'), +('cat_online', 'DE', 'Online'), +('cat_desc_luck', 'DE', 'Harte Konsequenzen: Goldbeutel, Tischeinsätze, Divine Punishment & The Devil''s Deal.'), +('cat_desc_solo', 'DE', 'Reines Kalkül gegen das Deck — eigene Fortschritts- und Rückstufungsregeln ohne Gold-Zwang.'), +('cat_desc_party_offline', 'DE', 'Klassische Gesellschaftsrunden am lokalen Tisch gegen KI-Charaktere.'), +('cat_desc_online', 'DE', 'Kein Welpenschutz: Echte Gegner & entfesselte Bots auf Gottheit-Niveau!'), +('no_games_in_category', 'DE', 'In der Kategorie „{0}“ sind aktuell noch keine Spieltische geöffnet.'), + +('stats_view_topbar', 'DE', 'Spiel-Statistiken ({0})'), +('stats_select_game_lbl', 'DE', 'Spiel auswählen:'), +('stats_game_rank_info', 'DE', 'Dein Rang in {0}: {1} • Stufe {2} ({3} / {4} XP)'), +('stats_game_board_title', 'DE', 'Statistik für {0}'), +('stats_all_variants_of_game', 'DE', 'Alle {0}-Spiele (Gesamt)'), +('stat_played', 'DE', 'Gespielte Spiele'), +('stat_won', 'DE', 'Gewonnene Spiele'), +('stat_lost', 'DE', 'Verlorene Spiele'), +('stat_win_pct', 'DE', 'Gewonnen in %'), +('stat_current_streak', 'DE', 'Aktuelle Siegesserie'), +('stat_longest_streak', 'DE', 'Längste Siegesserie'), +('stat_best_time', 'DE', 'Beste Spielzeit'), +('stat_avg_time', 'DE', 'Ø Spielzeit'), + +-- Audio-Einstellungen +('audio_title', 'DE', 'Audio & Atmosphäre'), +('audio_subtitle', 'DE', 'Einstellungen werden automatisch für das nächste Spiel gespeichert.'), +('audio_ambiance_label', 'DE', 'Ambiance & Hintergrundmusik'), +('audio_ambiance_desc', 'DE', 'Menü-Theme (Beyond the Iron Gate), Tisch-Musik (The Midnight Hand) & Stand-SFX'), +('audio_sfx_label', 'DE', 'Menü & Soundeffekte'), +('audio_sfx_desc', 'DE', 'Klicks, Karten geben, Sieg, Niederlage & Level-Aufstieg'), +('audio_test_btn', 'DE', 'Effekt testen'), +('audio_done_btn', 'DE', 'Fertig'), + +-- Spieltitel & Varianten +('game_title_blackjack', 'DE', 'Blackjack'), +('game_title_poker', 'DE', 'Texas Hold''em'), +('game_title_freecell', 'DE', 'FreeCell'), +('game_title_klondike', 'DE', 'Klondike'), +('game_title_spider_solitaire', 'DE', 'Spider Solitaire'), +('variant_bj_classic', 'DE', 'Blackjack – Klassisch'), +('variant_bj_highstakes', 'DE', 'Blackjack – Hoher Einsatz'), +('variant_poker_holdem', 'DE', 'Texas Hold''em – Klassisch'), +('variant_poker_holdem_high', 'DE', 'Texas Hold''em – Hoher Einsatz'), +('variant_klondike_1', 'DE', 'Klondike – 1 Karte ziehen'), +('variant_klondike_3', 'DE', 'Klondike – 3 Karten ziehen'), +('variant_freecell_std', 'DE', 'FreeCell – Standard'), +('variant_spider_1suit', 'DE', 'Spider – 1 Farbe'), +('variant_spider_2suit', 'DE', 'Spider – 2 Farben'), +('variant_spider_4suit', 'DE', 'Spider – 4 Farben'), + +-- Gegner / Bots (inkl. Stufe 6 Gottheit) +('none_bot', 'DE', '— Kein Gegner —'), +('opponent_label', 'DE', 'Gegner {0}:'), +('bot_default_name', 'DE', 'Kultist #{0}'), +('bot_level_0', 'DE', 'Stufe 0 – Verwirrte Seele (Zufall)'), +('bot_level_1', 'DE', 'Stufe 1 – Akolyth (Vorsichtig)'), +('bot_level_2', 'DE', 'Stufe 2 – Nachtwanderer (Solide)'), +('bot_level_3', 'DE', 'Stufe 3 – Schatten-Zocker (Dealer-Blick)'), +('bot_level_4', 'DE', 'Stufe 4 – Experte (Basisstrategie)'), +('bot_level_5', 'DE', 'Stufe 5 – Großmeister (Kartenzähler)'), +('bot_level_6', 'DE', 'Stufe 6 – Gottheit (Gnadenlos / Online-Standard)'), + +-- Blackjack Menü, Divine Punishment & The Devil's Deal +('bj_menu_topbar', 'DE', 'Blackjack – Konten & Tischauswahl'), +('bj_sec1_title', 'DE', '1. Blackjack-Goldkonto ({0}/{1} Beutel • Start: {2} Gold)'), +('bj_bots_sec_title', 'DE', '2. Gegner am Tisch (Gold abzocken!)'), +('bj_sec3_title', 'DE', '3. Spielvariante wählen'), +('bj_default_acc_name', 'DE', 'Goldbeutel #{0}'), +('bj_acc_dropdown_item', 'DE', '{0} — {1} Gold'), +('bj_active_acc_lbl', 'DE', 'Aktives Konto:'), +('bj_delete_acc_btn', 'DE', 'Konto löschen'), +('bj_new_acc_lbl', 'DE', 'Neues Konto:'), +('bj_create_acc_btn', 'DE', '+ Neues Konto ({0} Gold)'), +('bj_acc_limit_info', 'DE', 'Max. {0} Goldbeutel. Grundeinsatz immer {1} Gold, Erhöhungen nach Spiel-Level. Tausch: {2} XP → +{3} Gold.'), +('bj_max_acc_reached', 'DE', 'Maximum von {0} Goldbeuteln erreicht.'), +('bj_exchange_btn', 'DE', '{0} XP → +{1} Gold'), +('bj_exchange_divine_btn', 'DE', '† {0} XP → +{1} Gold'), +('bj_exchange_success', 'DE', '+{0} Gold für ''{1}'' eingetauscht (-{2} XP)!'), +('bj_exchange_divine_success', 'DE', 'GÖTTLICHE STRAFE! +{0} Gold für ''{1}'' erhalten (-{2} XP) — Sturz auf {3}!'), +('bj_divine_punishment_warn', 'DE', 'DIVINE PUNISHMENT: Kosten = 10x Ø-XP des Vorlevels ({0} XP → +{1} Gold). Max. Rückfall: Schöpfergeist V!'), +('bj_devils_deal_warn', 'DE', 'THE DEVIL''S DEAL: Abgrund von Schöpfergeist V erreicht! Opfere einen Account ab Stütze I (Lv. {0}+) für +{1} Gold:'), +('bj_devils_deal_btn', 'DE', '† Seele opfern (+{0} Gold)'), +('bj_devils_deal_none', 'DE', 'Keine opferbare Seele (mind. Rang Stütze I / Lv. {0} in diesem Spiel) vorhanden.'), +('bj_devils_deal_success', 'DE', 'THE DEVIL''S DEAL BESIEGELT! Seele ''{0}'' ausgelöscht — +{1} Gold für ''{2}''!'), +('devils_deal_locked_badge', 'DE', '† DEVIL''S DEAL AKTIV — Flucht unmöglich'), +('devils_deal_resume_title', 'DE', '† THE DEVIL''S DEAL AKTIV †'), +('devils_deal_resume_desc', 'DE', 'Deine Seele ist an den Spieltisch gebunden. Andere Spiele sind gesperrt, bis der Pakt entschieden ist!'), +('devils_deal_resume_card', 'DE', 'Pakt fortsetzen' || char(10) || '(Resume)'), +('bj_err_floor_reached', 'DE', 'Schöpfergeist V Untergrenze erreicht! Nutze The Devil''s Deal oder verdiene neue XP.'), +('bj_err_empty_name', 'DE', 'Bitte gib einen Kontonamen ein.'), +('bj_err_duplicate_name', 'DE', 'Ein Blackjack-Konto mit diesem Namen existiert bereits.'), +('bj_err_not_enough_xp', 'DE', 'Nicht genug XP ({0}/{1} XP). Verdiene erst mehr XP mit einem anderen Goldbeutel!'), +('bj_err_not_enough_gold_entry', 'DE', '''{0}'' hat weniger als {1} Gold ({2} Gold)! Tausche {3} XP gegen +{4} Gold oder wechsle den Goldbeutel.'), +('bj_err_not_enough_gold_table', 'DE', '''{0}'' hat nur {1} Gold – dieser Tisch erfordert mindestens {2} Gold.'), +('bj_err_not_enough_gold_menu', 'DE', '''{0}'' hat nur noch {1} Gold (Mindesteinsatz: {2} Gold). Wähle oder erstelle ein anderes Konto!'), +('bj_variant_desc', 'DE', '{0} Decks • Grundeinsatz: {1} Gold • Devil''s Gambit • Dealer hält ab 17 • 7-7-7 = Sofortsieg'), +('bj_enter_table_btn', 'DE', 'Tisch betreten'), +('bj_filter_all_tables', 'DE', 'Dieses Konto (Alle Blackjack-Tische)'), +('bj_stats_acc_title', 'DE', 'Konto-Statistik: {0}'), + +-- Blackjack Tisch, Devil's Gambit & 4-Stufen-Ablaufbaum +('bj_header_gold', 'DE', 'Konto ''{0}'': {1} Gold'), +('bj_pot_banner', 'DE', 'GOLD-POT: {0} Gold | Höchsteinsatz am Tisch: {1} Gold'), +('bj_dealer_title', 'DE', 'Haus-Dealer (zieht bis 16, hält ab 17)'), +('bj_dealer_shows', 'DE', 'Haus-Dealer zeigt: {0} (1 Karte verdeckt)'), +('bj_dealer_total', 'DE', 'Haus-Dealer: {0}'), +('bj_player_title', 'DE', 'Deine Hand'), +('bj_player_total', 'DE', 'Deine Hand: {0}{1} | Im Pot: {2} Gold{3}'), +('bj_hand_box_title', 'DE', 'Hand {0}: {1}{2} • Pot: {3}g{4}'), +('bj_state_locked', 'DE', ' [FERTIG]'), +('bj_state_busted', 'DE', ' [OUT >21]'), +('bj_state_folded', 'DE', ' [RAUS]'), +('bj_active_hand_tag', 'DE', ' (Hand {0})'), +('bj_soft_hint', 'DE', ' (Soft {0})'), +('bj_out_of_gold_table', 'DE', 'Konto ''{0}'' hat nur noch {1} Gold (Tisch-Minimum: {2} Gold).'), +('bj_back_to_acc_menu_btn', 'DE', '← Zum Kontomenü (Neues Konto wählen/erstellen)'), +('bj_pre_deal_prompt', 'DE', 'Bereit für die nächste Runde? Grundeinsatz beim Austeilen: {0} Gold pro Person.'), +('bj_deal_btn', 'DE', 'Karten geben ({0} Gold)'), + +('bj_turn_prompt', 'DE', 'Dein Zug! Setze Gold, ziehe eine Karte oder melde ''Fertig''.'), +('bj_turn_call_needed', 'DE', 'Dein Zug! Zum Mitgehen fehlen {0} Gold – begleiche, erhöhe oder steige aus.'), +('bj_turn_prompt_open', 'DE', 'Dein Zug{0}: Karte ziehen / Verdoppeln / Teilen optional — dann Fertig, Mitziehen, Erhöhen oder Austreten.'), +('bj_turn_prompt_post_card', 'DE', 'Karte gezogen{0}! Wähle jetzt: Mitziehen, Fertig (Karten fest), Erhöhen oder Austreten.'), +('bj_turn_prompt_locked_call', 'DE', 'Erhöhung am Tisch (+{1} Gold){0}! Deine Karten stehen fest — Mitziehen, Erhöhen oder Austreten?'), +('bj_turn_prompt_open_call', 'DE', 'Erhöhung am Tisch (+{1} Gold){0}! Du darfst vorher 1 Karte ziehen — dann Mitziehen, Erhöhen oder Austreten.'), + +('bj_tree_step1_call', 'DE', '1. Mitgehen{0}? Zum Weiterspielen musst du +{1} Gold mitgehen — sonst bist du raus (Verloren)!'), +('bj_tree_step1_even', 'DE', '1. Weiterspielen{0}? Wähle Mitgehen für deinen Zug oder markiere dich direkt als Fertig.'), +('bj_tree_btn_call_yes', 'DE', 'Ja, Mitgehen (+{0} Gold)'), +('bj_tree_btn_play_yes', 'DE', 'Ja, Mitgehen (Weiterspielen)'), +('bj_tree_btn_call_no_lose', 'DE', 'Nein — Austreten (Verloren)'), +('bj_tree_btn_even_no_done', 'DE', 'Nein — Als Fertig markieren'), +('bj_tree_step2_draw', 'DE', '2. Karte ziehen{0}? Möchtest du eine Karte nehmen?'), +('bj_tree_btn_draw_yes', 'DE', 'Ja, Karte ziehen!'), +('bj_tree_btn_draw_no', 'DE', 'Nein, keine Karte'), +('bj_tree_step3_raise', 'DE', '3. Einsatz erhöhen{0}? Wähle einen Betrag zum Erhöhen oder gehe ohne Erhöhung weiter.'), +('bj_tree_btn_raise_no', 'DE', 'Nein (Nicht erhöhen)'), +('bj_tree_step4_done', 'DE', '4. Fertig{0}? Sollen deine Karten feststehen oder bleibst du für die nächste Runde offen?'), +('bj_tree_btn_done_yes', 'DE', 'Ja — Fertig (Karten fest)'), +('bj_tree_btn_done_no', 'DE', 'Nein — Weiter (Nächster dran)'), + +('bj_raise_lbl', 'DE', 'Erhöhen:'), +('bj_call_btn', 'DE', 'Mitziehen (+{0})'), +('bj_call_ready_btn', 'DE', 'Mitziehen & Fertig (+{0})'), +('bj_check_btn', 'DE', 'Mitziehen (Weiter)'), +('bj_hit_btn', 'DE', 'Karte ziehen (Hit)'), +('bj_double_btn', 'DE', 'Verdoppeln (+{0})'), +('bj_split_btn', 'DE', 'Teilen (+{0})'), +('bj_ready_btn', 'DE', 'Fertig (Halten)'), +('bj_fold_btn', 'DE', 'Austreten'), + +('bj_bot_turn_status', 'DE', '{0} überlegt...'), +('bj_bot_gold_lbl', 'DE', 'Beutel: {0} Gold'), +('bj_bot_cards_hidden', 'DE', '{0} Karten • Pot: {1} Gold'), +('bj_bot_action_bet', 'DE', 'Erhöht (+{0})'), +('bj_bot_action_call', 'DE', 'Geht mit (+{0})'), +('bj_bot_action_hit', 'DE', 'Zieht Karte ({0})'), +('bj_bot_action_double', 'DE', 'Verdoppelt! (+{0})'), +('bj_bot_action_check', 'DE', 'Zieht mit ({0} K.)'), +('bj_bot_action_ready', 'DE', 'Fertig ({0} Karten)'), +('bj_bot_action_bust', 'DE', 'OUT! Überkauft ({0})'), +('bj_bot_action_fold', 'DE', 'Ausgetreten'), +('bj_bot_showdown_val', 'DE', '{0} Punkte • Einsatz: {1}'), +('bj_bot_rebuy', 'DE', '{0} (Neukauf)'), +('bj_dealer_reveals', 'DE', 'Alle fertig! Karten werden aufgedeckt & Haus-Dealer zieht...'), +('bj_next_hand_btn', 'DE', 'Nächste Runde'), +('bj_xp_gain_suffix', 'DE', ' (+{0} XP)'), +('bj_level_up_suffix', 'DE', ' ★ LEVEL UP! Stufe {0}!'), + +-- Ergebnis-Popup +('bj_popup_bank_won', 'DE', 'Die Bank hat gewonnen'), +('bj_popup_player_won', 'DE', 'Du hast gewonnen'), +('bj_popup_bot_won', 'DE', 'Spieler {0} hat gewonnen'), +('bj_popup_tie', 'DE', 'Unentschieden mit der Bank'), +('bj_popup_your_gain', 'DE', 'Dein Gewinn: +{0} Gold'), +('bj_popup_your_loss', 'DE', 'Dein Verlust: -{0} Gold'), +('bj_popup_your_even', 'DE', 'Dein Ergebnis: ±0 Gold (Einsatz zurück)'), +('bj_popup_bank_gain', 'DE', 'Gewinn der Bank: +{0} Gold'), +('bj_popup_bot_gain', 'DE', 'Gewinn von {0}: +{1} Gold'), +('bj_popup_xp_earned', 'DE', 'Verdiente Erfahrung: +{0} XP'), +('bj_popup_level_up', 'DE', '★ AUFSTIEG! Stufe {0} — {1}!'), +('bj_popup_next_round_btn', 'DE', 'Nächste Runde starten'), +('bj_popup_to_menu_btn', 'DE', 'Zum Spielmenü'); + +-- ========================================================================= +-- 5. ALLE ÜBERSETZUNGEN (EN) +-- ========================================================================= + +INSERT INTO base_i18n (key, lang, val) VALUES +-- Global & Navigation +('app_title', 'EN', 'The Goth Cardgame Collection'), +('header_title', 'EN', 'GOTH CARD COLLECTION'), +('btn_audio', 'EN', 'Audio'), +('btn_lang', 'EN', 'Lang: EN'), +('btn_stats', 'EN', 'Statistics'), +('btn_back_main', 'EN', '← Main Menu'), +('btn_back_game_menu', 'EN', '← Game Menu'), +('btn_switch_profile', 'EN', '← Switch Profile'), +('level_badge', 'EN', '{0} • {1} (Lv. {2} | {3}/{4} XP)'), +('main_acc_header', 'EN', '{0} • {1} (Lv. {2} | {3} XP)'), +('main_acc_soul_only', 'EN', 'Soul: {0}'), +('menu_card_rank_sub', 'EN', '{0}' || char(10) || 'Lv. {1}'), +('xp_next_level', 'EN', '{0} / {1} XP to Lv. {2}'), + +-- Login +('login_select_lbl', 'EN', 'Select existing profile:'), +('login_create_lbl', 'EN', 'Create a new soul profile:'), +('login_btn', 'EN', 'Log In'), +('new_profile_btn', 'EN', 'New Account'), + +-- Main Menu, 4 Categories & Game Statistics +('choose_cardgame', 'EN', 'Choose a Card Game'), +('no_games_found', 'EN', 'No start.py found inside games/ yet.'), +('cat_luck', 'EN', 'Luck'), +('cat_solo', 'EN', 'Solo'), +('cat_party_offline', 'EN', 'Party - Offline'), +('cat_online', 'EN', 'Online'), +('cat_desc_luck', 'EN', 'Harsh consequences: Gold pouches, table stakes, Divine Punishment & The Devil''s Deal.'), +('cat_desc_solo', 'EN', 'Pure calculation against the deck — dedicated progression & demotion rules without Gold.'), +('cat_desc_party_offline', 'EN', 'Classic parlor card games at the local table against AI personalities.'), +('cat_desc_online', 'EN', 'No hand-holding: Real opponents & unleashed bots operating at Deity rank!'), +('no_games_in_category', 'EN', 'No tables are currently open in category "{0}".'), + +('stats_view_topbar', 'EN', 'Game Statistics ({0})'), +('stats_select_game_lbl', 'EN', 'Select Game:'), +('stats_game_rank_info', 'EN', 'Your Rank in {0}: {1} • Level {2} ({3} / {4} XP)'), +('stats_game_board_title', 'EN', 'Statistics for {0}'), +('stats_all_variants_of_game', 'EN', 'All {0} Games (Total)'), +('stat_played', 'EN', 'Games Played'), +('stat_won', 'EN', 'Games Won'), +('stat_lost', 'EN', 'Games Lost'), +('stat_win_pct', 'EN', 'Win Rate %'), +('stat_current_streak', 'EN', 'Current Win Streak'), +('stat_longest_streak', 'EN', 'Longest Win Streak'), +('stat_best_time', 'EN', 'Best Time'), +('stat_avg_time', 'EN', 'Avg. Time'), + +-- Audio Settings +('audio_title', 'EN', 'Audio & Atmosphere'), +('audio_subtitle', 'EN', 'Settings are automatically saved for your next session.'), +('audio_ambiance_label', 'EN', 'Ambiance & Background Music'), +('audio_ambiance_desc', 'EN', 'Menu theme (Beyond the Iron Gate), table music (The Midnight Hand) & stand SFX'), +('audio_sfx_label', 'EN', 'Menu & Sound Effects'), +('audio_sfx_desc', 'EN', 'Clicks, dealing cards, victory, defeat & level-up'), +('audio_test_btn', 'EN', 'Test Effect'), +('audio_done_btn', 'EN', 'Done'), + +-- Game Titles & Variants +('game_title_blackjack', 'EN', 'Blackjack'), +('game_title_poker', 'EN', 'Texas Hold''em'), +('game_title_freecell', 'EN', 'FreeCell'), +('game_title_klondike', 'EN', 'Klondike'), +('game_title_spider_solitaire', 'EN', 'Spider Solitaire'), +('variant_bj_classic', 'EN', 'Blackjack – Classic'), +('variant_bj_highstakes', 'EN', 'Blackjack – High Stakes'), +('variant_poker_holdem', 'EN', 'Texas Hold''em – Classic'), +('variant_poker_holdem_high', 'EN', 'Texas Hold''em – High Stakes'), +('variant_klondike_1', 'EN', 'Klondike – Draw 1'), +('variant_klondike_3', 'EN', 'Klondike – Draw 3'), +('variant_freecell_std', 'EN', 'FreeCell – Standard'), +('variant_spider_1suit', 'EN', 'Spider – 1 Suit'), +('variant_spider_2suit', 'EN', 'Spider – 2 Suits'), +('variant_spider_4suit', 'EN', 'Spider – 4 Suits'), + +-- Bots (incl. Level 6 Deity) +('none_bot', 'EN', '— No Opponent —'), +('opponent_label', 'EN', 'Opponent {0}:'), +('bot_default_name', 'EN', 'Cultist #{0}'), +('bot_level_0', 'EN', 'Level 0 – Lost Soul (Random)'), +('bot_level_1', 'EN', 'Level 1 – Acolyte (Cautious)'), +('bot_level_2', 'EN', 'Level 2 – Nightwalker (Solid)'), +('bot_level_3', 'EN', 'Level 3 – Shadow Gambler (Upcard Aware)'), +('bot_level_4', 'EN', 'Level 4 – Expert (Basic Strategy)'), +('bot_level_5', 'EN', 'Level 5 – Grandmaster (Card Counter)'), +('bot_level_6', 'EN', 'Level 6 – Deity (Merciless / Online Standard)'), + +-- Blackjack Menu, Divine Punishment & The Devil's Deal +('bj_menu_topbar', 'EN', 'Blackjack – Accounts & Table Selection'), +('bj_sec1_title', 'EN', '1. Blackjack Gold Account ({0}/{1} Pouches • Start: {2} Gold)'), +('bj_bots_sec_title', 'EN', '2. Opponents at the Table (Win their Gold!)'), +('bj_sec3_title', 'EN', '3. Choose Game Variant'), +('bj_default_acc_name', 'EN', 'Gold Pouch #{0}'), +('bj_acc_dropdown_item', 'EN', '{0} — {1} Gold'), +('bj_active_acc_lbl', 'EN', 'Active Account:'), +('bj_delete_acc_btn', 'EN', 'Delete Account'), +('bj_new_acc_lbl', 'EN', 'New Account:'), +('bj_create_acc_btn', 'EN', '+ New Account ({0} Gold)'), +('bj_acc_limit_info', 'EN', 'Max {0} Pouches. Initial ante always {1} Gold, raises scale with Game Level. Exchange: {2} XP → +{3} Gold.'), +('bj_max_acc_reached', 'EN', 'Maximum of {0} Gold Pouches reached.'), +('bj_exchange_btn', 'EN', '{0} XP → +{1} Gold'), +('bj_exchange_divine_btn', 'EN', '† {0} XP → +{1} Gold'), +('bj_exchange_success', 'EN', 'Exchanged -{2} XP for +{0} Gold on ''{1}''!'), +('bj_exchange_divine_success', 'EN', 'DIVINE PUNISHMENT! +{0} Gold on ''{1}'' (-{2} XP) — Fallen to {3}!'), +('bj_divine_punishment_warn', 'EN', 'DIVINE PUNISHMENT: Cost = 10x avg XP of previous level ({0} XP → +{1} Gold). Max drop: Creator Spirit V!'), +('bj_devils_deal_warn', 'EN', 'THE DEVIL''S DEAL: Floor of Creator Spirit V reached! Sacrifice a profile at Support I (Lv. {0}+) for +{1} Gold:'), +('bj_devils_deal_btn', 'EN', '† Sacrifice Soul (+{0} Gold)'), +('bj_devils_deal_none', 'EN', 'No sacrificeable soul (min. Support I / Lv. {0} in this game) available.'), +('bj_devils_deal_success', 'EN', 'THE DEVIL''S DEAL SEALED! Soul ''{0}'' erased — +{1} Gold for ''{2}''!'), +('devils_deal_locked_badge', 'EN', '† DEVIL''S DEAL ACTIVE — No Escape'), +('devils_deal_resume_title', 'EN', '† THE DEVIL''S DEAL ACTIVE †'), +('devils_deal_resume_desc', 'EN', 'Your soul is bound to the table. Other games are locked until the pact is resolved!'), +('devils_deal_resume_card', 'EN', 'Resume Pact' || char(10) || '(Continue)'), +('bj_err_floor_reached', 'EN', 'Creator Spirit V floor reached! Use The Devil''s Deal or earn more XP.'), +('bj_err_empty_name', 'EN', 'Please enter an account name.'), +('bj_err_duplicate_name', 'EN', 'A Blackjack account with this name already exists.'), +('bj_err_not_enough_xp', 'EN', 'Not enough XP ({0}/{1} XP). Earn more XP with another pouch first!'), +('bj_err_not_enough_gold_entry', 'EN', '''{0}'' has less than {1} Gold ({2} Gold)! Exchange {3} XP for +{4} Gold or switch pouches.'), +('bj_err_not_enough_gold_table', 'EN', '''{0}'' only has {1} Gold – this table requires at least {2} Gold.'), +('bj_err_not_enough_gold_menu', 'EN', '''{0}'' only has {1} Gold left (Minimum: {2} Gold). Select or create another account!'), +('bj_variant_desc', 'EN', '{0} Decks • Initial Ante: {1} Gold • Devil''s Gambit • Dealer stands on 17 • 7-7-7 = Instant Win'), +('bj_enter_table_btn', 'EN', 'Enter Table'), +('bj_filter_all_tables', 'EN', 'This Account (All Blackjack Tables)'), +('bj_stats_acc_title', 'EN', 'Account Stats: {0}'), + +-- Blackjack Table, Devil's Gambit & 4-Step Flowchart +('bj_header_gold', 'EN', 'Account ''{0}'': {1} Gold'), +('bj_pot_banner', 'EN', 'GOLD POT: {0} Gold | Current Table Bet: {1} Gold'), +('bj_dealer_title', 'EN', 'House Dealer (hits up to 16, stands on 17)'), +('bj_dealer_shows', 'EN', 'House Dealer shows: {0} (1 hole card)'), +('bj_dealer_total', 'EN', 'House Dealer: {0}'), +('bj_player_title', 'EN', 'Your Hand'), +('bj_player_total', 'EN', 'Your Hand: {0}{1} | In Pot: {2} Gold{3}'), +('bj_hand_box_title', 'EN', 'Hand {0}: {1}{2} • Pot: {3}g{4}'), +('bj_state_locked', 'EN', ' [LOCKED]'), +('bj_state_busted', 'EN', ' [OUT >21]'), +('bj_state_folded', 'EN', ' [FOLDED]'), +('bj_active_hand_tag', 'EN', ' (Hand {0})'), +('bj_soft_hint', 'EN', ' (Soft {0})'), +('bj_out_of_gold_table', 'EN', 'Account ''{0}'' only has {1} Gold left (Table minimum: {2} Gold).'), +('bj_back_to_acc_menu_btn', 'EN', '← Account Menu (Switch/Create Account)'), +('bj_pre_deal_prompt', 'EN', 'Ready for the next hand? Entry ante on deal: {0} Gold per player.'), +('bj_deal_btn', 'EN', 'Deal Cards ({0} Gold)'), + +('bj_turn_prompt', 'EN', 'Your turn! Bet Gold, draw a card, or declare ''Ready''.'), +('bj_turn_call_needed', 'EN', 'Your turn! {0} Gold needed to match the bet – call, raise, or fold.'), +('bj_turn_prompt_open', 'EN', 'Your turn{0}: Draw / Double / Split optional — then Stand, Check, Raise, or Leave.'), +('bj_turn_prompt_post_card', 'EN', 'Card drawn{0}! Choose now: Check/Call, Stand (lock cards), Raise, or Leave.'), +('bj_turn_prompt_locked_call', 'EN', 'Bet raised (+{1} Gold){0}! Your cards are locked — Call, Raise, or Leave?'), +('bj_turn_prompt_open_call', 'EN', 'Bet raised (+{1} Gold){0}! You may draw 1 card first — then Call, Raise, or Leave.'), + +('bj_tree_step1_call', 'EN', '1. Match Bet{0}? Pay +{1} Gold to stay in — otherwise you are out (Lost)!'), +('bj_tree_step1_even', 'EN', '1. Continue Playing{0}? Choose Continue for your turn, or mark yourself Ready right now.'), +('bj_tree_btn_call_yes', 'EN', 'Yes, Match (+{0} Gold)'), +('bj_tree_btn_play_yes', 'EN', 'Yes, Continue Playing'), +('bj_tree_btn_call_no_lose', 'EN', 'No — Leave (Lost)'), +('bj_tree_btn_even_no_done', 'EN', 'No — Mark as Ready'), +('bj_tree_step2_draw', 'EN', '2. Draw Card{0}? Would you like to take a card?'), +('bj_tree_btn_draw_yes', 'EN', 'Yes, Draw Card!'), +('bj_tree_btn_draw_no', 'EN', 'No Card'), +('bj_tree_step3_raise', 'EN', '3. Raise Bet{0}? Pick a chip to raise, or continue without raising.'), +('bj_tree_btn_raise_no', 'EN', 'No Raise'), +('bj_tree_step4_done', 'EN', '4. Ready{0}? Lock your cards now, or stay open for the next round?'), +('bj_tree_btn_done_yes', 'EN', 'Yes — Ready (Lock Cards)'), +('bj_tree_btn_done_no', 'EN', 'No — Next Player'), + +('bj_raise_lbl', 'EN', 'Raise:'), +('bj_call_btn', 'EN', 'Call (+{0})'), +('bj_call_ready_btn', 'EN', 'Call & Stand (+{0})'), +('bj_check_btn', 'EN', 'Check (Continue)'), +('bj_hit_btn', 'EN', 'Draw Card (Hit)'), +('bj_double_btn', 'EN', 'Double Down (+{0})'), +('bj_split_btn', 'EN', 'Split (+{0})'), +('bj_ready_btn', 'EN', 'Ready (Stand)'), +('bj_fold_btn', 'EN', 'Leave (Fold)'), + +('bj_bot_turn_status', 'EN', '{0} is acting...'), +('bj_bot_gold_lbl', 'EN', 'Pouch: {0} Gold'), +('bj_bot_cards_hidden', 'EN', '{0} Cards • Pot: {1} Gold'), +('bj_bot_action_bet', 'EN', 'Raises (+{0})'), +('bj_bot_action_call', 'EN', 'Matches (+{0})'), +('bj_bot_action_hit', 'EN', 'Draws card ({0})'), +('bj_bot_action_double', 'EN', 'Doubled! (+{0})'), +('bj_bot_action_check', 'EN', 'Checks ({0} c.)'), +('bj_bot_action_ready', 'EN', 'Ready ({0} cards)'), +('bj_bot_action_bust', 'EN', 'OUT! Bust ({0})'), +('bj_bot_action_fold', 'EN', 'Left Hand'), +('bj_bot_showdown_val', 'EN', '{0} pts • Bet: {1}'), +('bj_bot_rebuy', 'EN', '{0} (Rebuy)'), +('bj_dealer_reveals', 'EN', 'Everyone ready! Showdown & House Dealer draws...'), +('bj_next_hand_btn', 'EN', 'Next Round'), +('bj_xp_gain_suffix', 'EN', ' (+{0} XP)'), +('bj_level_up_suffix', 'EN', ' ★ LEVEL UP! Level {0}!'), + +-- Result Popup +('bj_popup_bank_won', 'EN', 'The House Won'), +('bj_popup_player_won', 'EN', 'You Won'), +('bj_popup_bot_won', 'EN', 'Player {0} Won'), +('bj_popup_tie', 'EN', 'Push with the House'), +('bj_popup_your_gain', 'EN', 'Your Profit: +{0} Gold'), +('bj_popup_your_loss', 'EN', 'Your Loss: -{0} Gold'), +('bj_popup_your_even', 'EN', 'Your Result: ±0 Gold (Bet returned)'), +('bj_popup_bank_gain', 'EN', 'House Profit: +{0} Gold'), +('bj_popup_bot_gain', 'EN', 'Profit of {0}: +{1} Gold'), +('bj_popup_xp_earned', 'EN', 'Experience Earned: +{0} XP'), +('bj_popup_level_up', 'EN', '★ LEVEL UP! Level {0} — {1}!'), +('bj_popup_next_round_btn', 'EN', 'Start Next Round'), +('bj_popup_to_menu_btn', 'EN', 'Back to Game Menu'); + +COMMIT; \ No newline at end of file diff --git a/resources/code_res/sql_queries.py b/resources/code_res/sql_queries.py new file mode 100644 index 0000000..9485730 --- /dev/null +++ b/resources/code_res/sql_queries.py @@ -0,0 +1,303 @@ +# -*- coding: utf-8 -*- +# resources/code_res/sql_queries.py + +PRAGMA_FOREIGN_KEYS = "PRAGMA foreign_keys = ON;" +ATTACH_INTERNAL_DB = "ATTACH DATABASE ? AS core;" + +USER_SCHEMA_DDL = """ +CREATE TABLE IF NOT EXISTS settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL +); + +CREATE TABLE IF NOT EXISTS profiles ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT UNIQUE NOT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +CREATE TABLE IF NOT EXISTS game_progress ( + profile_id INTEGER NOT NULL, + game_folder TEXT NOT NULL, + points INTEGER NOT NULL DEFAULT 0, + ever_reached_deity INTEGER NOT NULL DEFAULT 0, + PRIMARY KEY (profile_id, game_folder), + FOREIGN KEY (profile_id) REFERENCES profiles(id) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS game_level_xp_history ( + profile_id INTEGER NOT NULL, + game_folder TEXT NOT NULL, + level_num INTEGER NOT NULL, + games_count INTEGER NOT NULL DEFAULT 0, + total_xp_earned INTEGER NOT NULL DEFAULT 0, + PRIMARY KEY (profile_id, game_folder, level_num), + FOREIGN KEY (profile_id) REFERENCES profiles(id) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS savegames ( + profile_id INTEGER NOT NULL, + game_folder TEXT NOT NULL, + variant_key TEXT NOT NULL, + state_json TEXT NOT NULL, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (profile_id, game_folder), + FOREIGN KEY (profile_id) REFERENCES profiles(id) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS blackjack_accounts ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + profile_id INTEGER NOT NULL, + account_name TEXT NOT NULL, + gold INTEGER NOT NULL DEFAULT 1000, + last_bet INTEGER NOT NULL DEFAULT 10, + devils_deal_active INTEGER NOT NULL DEFAULT 0, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + UNIQUE(profile_id, account_name), + FOREIGN KEY (profile_id) REFERENCES profiles(id) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS player_stats ( + profile_id INTEGER NOT NULL, + variant_id INTEGER NOT NULL, + games_played INTEGER NOT NULL DEFAULT 0, + games_won INTEGER NOT NULL DEFAULT 0, + games_lost INTEGER NOT NULL DEFAULT 0, + current_streak INTEGER NOT NULL DEFAULT 0, + longest_streak INTEGER NOT NULL DEFAULT 0, + best_time_sec REAL DEFAULT NULL, + total_time_sec REAL NOT NULL DEFAULT 0.0, + PRIMARY KEY (profile_id, variant_id), + FOREIGN KEY (profile_id) REFERENCES profiles(id) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS blackjack_account_stats ( + bj_account_id INTEGER NOT NULL, + variant_id INTEGER NOT NULL, + games_played INTEGER NOT NULL DEFAULT 0, + games_won INTEGER NOT NULL DEFAULT 0, + games_lost INTEGER NOT NULL DEFAULT 0, + current_streak INTEGER NOT NULL DEFAULT 0, + longest_streak INTEGER NOT NULL DEFAULT 0, + best_time_sec REAL DEFAULT NULL, + total_time_sec REAL NOT NULL DEFAULT 0.0, + PRIMARY KEY (bj_account_id, variant_id), + FOREIGN KEY (bj_account_id) REFERENCES blackjack_accounts(id) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS bot_configs ( + profile_id INTEGER NOT NULL, + game_folder TEXT NOT NULL, + slot_idx INTEGER NOT NULL, + bot_name TEXT NOT NULL, + ai_level INTEGER NOT NULL DEFAULT -1, + PRIMARY KEY (profile_id, game_folder, slot_idx), + FOREIGN KEY (profile_id) REFERENCES profiles(id) ON DELETE CASCADE +); +""" + +PRAGMA_TABLE_INFO_BJ_ACCOUNTS = "PRAGMA table_info(blackjack_accounts);" +MIGRATE_ADD_DEVILS_ACTIVE = "ALTER TABLE blackjack_accounts ADD COLUMN devils_deal_active INTEGER NOT NULL DEFAULT 0;" + +# --- Interne Stammdaten (core = internal_base.db) --- +SELECT_ALL_I18N = "SELECT lang, key, val FROM core.base_i18n;" +SELECT_PRESTIGE_RANKS = "SELECT rank_idx, title_de, title_en FROM core.base_prestige_ranks ORDER BY rank_idx ASC;" +SELECT_VARIANT_INFO_BY_KEY = "SELECT id, folder_path FROM core.game_variants WHERE variant_key = ?;" +SELECT_VARIANTS_BY_FOLDER = "SELECT id, variant_key, display_name FROM core.game_variants WHERE folder_path = ? ORDER BY id;" +SELECT_ALL_VARIANTS = "SELECT id, variant_key, display_name FROM core.game_variants ORDER BY id;" + +# --- Settings (user_data.db) --- +SELECT_SETTING = "SELECT value FROM settings WHERE key = ?;" +UPSERT_SETTING = """ +INSERT INTO settings (key, value) VALUES (?, ?) +ON CONFLICT(key) DO UPDATE SET value = excluded.value; +""" + +# --- Profiles (rein Account-Identität, ohne globales Level!) --- +SELECT_ALL_PROFILES = "SELECT name FROM profiles ORDER BY name COLLATE NOCASE;" +INSERT_PROFILE_IGNORE = "INSERT OR IGNORE INTO profiles (name) VALUES (?);" +SELECT_PROFILE_BY_NAME = "SELECT id, name FROM profiles WHERE name = ?;" +SELECT_PROFILE_BY_ID = "SELECT id, name FROM profiles WHERE id = ?;" +DELETE_PROFILE_BY_ID = "DELETE FROM profiles WHERE id = ?;" + +# --- Spielgebundene Progression & Level-Historie (pro profile_id + game_folder) --- +INSERT_GAME_PROGRESS_IGNORE = """ +INSERT OR IGNORE INTO game_progress (profile_id, game_folder, points, ever_reached_deity) +VALUES (?, ?, 0, 0); +""" +SELECT_GAME_PROGRESS = """ +SELECT profile_id, game_folder, points, ever_reached_deity +FROM game_progress +WHERE profile_id = ? AND game_folder = ?; +""" +ADD_GAME_POINTS = """ +UPDATE game_progress +SET points = points + ? +WHERE profile_id = ? AND game_folder = ?; +""" +SET_GAME_POINTS = """ +UPDATE game_progress +SET points = ? +WHERE profile_id = ? AND game_folder = ?; +""" +MARK_GAME_EVER_DEITY = """ +UPDATE game_progress +SET ever_reached_deity = 1 +WHERE profile_id = ? AND game_folder = ?; +""" +SELECT_CANDIDATES_FOR_GAME_SACRIFICE = """ +SELECT p.id, p.name, gp.points, gp.ever_reached_deity +FROM profiles p +JOIN game_progress gp ON gp.profile_id = p.id +WHERE gp.game_folder = ? AND p.id != ? +ORDER BY gp.points DESC; +""" + +UPSERT_GAME_LEVEL_XP_HISTORY = """ +INSERT INTO game_level_xp_history (profile_id, game_folder, level_num, games_count, total_xp_earned) +VALUES (?, ?, ?, 1, ?) +ON CONFLICT(profile_id, game_folder, level_num) DO UPDATE SET + games_count = game_level_xp_history.games_count + 1, + total_xp_earned = game_level_xp_history.total_xp_earned + excluded.total_xp_earned; +""" +SELECT_GAME_LEVEL_AVG_XP = """ +SELECT games_count, total_xp_earned +FROM game_level_xp_history +WHERE profile_id = ? AND game_folder = ? AND level_num = ?; +""" + +# --- Savegames --- +SELECT_SAVEGAME = "SELECT variant_key, state_json FROM savegames WHERE profile_id = ? AND game_folder = ?;" +UPSERT_SAVEGAME = """ +INSERT INTO savegames (profile_id, game_folder, variant_key, state_json, updated_at) +VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP) +ON CONFLICT(profile_id, game_folder) DO UPDATE SET + variant_key = excluded.variant_key, + state_json = excluded.state_json, + updated_at = CURRENT_TIMESTAMP; +""" +DELETE_SAVEGAME = "DELETE FROM savegames WHERE profile_id = ? AND game_folder = ?;" + +# --- Blackjack Gold Accounts --- +SELECT_BJ_ACCOUNTS_BY_PROFILE = """ +SELECT id, profile_id, account_name, gold, last_bet, devils_deal_active +FROM blackjack_accounts WHERE profile_id = ? ORDER BY id ASC; +""" +SELECT_BJ_ACCOUNT_BY_ID = """ +SELECT id, profile_id, account_name, gold, last_bet, devils_deal_active +FROM blackjack_accounts WHERE id = ?; +""" +SELECT_BJ_ACCOUNT_BY_NAME = """ +SELECT id, profile_id, account_name, gold, last_bet, devils_deal_active +FROM blackjack_accounts WHERE profile_id = ? AND account_name = ?; +""" +SELECT_ACTIVE_DEVILS_BJ_ACCOUNT = """ +SELECT id, profile_id, account_name, gold, last_bet, devils_deal_active +FROM blackjack_accounts +WHERE profile_id = ? AND devils_deal_active = 1 +LIMIT 1; +""" +INSERT_BJ_ACCOUNT = "INSERT INTO blackjack_accounts (profile_id, account_name, gold, last_bet, devils_deal_active) VALUES (?, ?, ?, ?, 0);" +UPDATE_BJ_GOLD_AND_BET = "UPDATE blackjack_accounts SET gold = MAX(0, gold + ?), last_bet = ? WHERE id = ?;" +UPDATE_BJ_GOLD_ONLY = "UPDATE blackjack_accounts SET gold = MAX(0, gold + ?) WHERE id = ?;" +UPDATE_BJ_LAST_BET = "UPDATE blackjack_accounts SET last_bet = ? WHERE id = ?;" +SET_BJ_DEVILS_DEAL_ACTIVE = "UPDATE blackjack_accounts SET devils_deal_active = ? WHERE id = ?;" +DELETE_BJ_ACCOUNT = "DELETE FROM blackjack_accounts WHERE id = ?;" + +# --- Bot Configs --- +SELECT_BOT_CONFIGS = "SELECT slot_idx, bot_name, ai_level FROM bot_configs WHERE profile_id = ? AND game_folder = ? ORDER BY slot_idx ASC;" +UPSERT_BOT_CONFIG = """ +INSERT INTO bot_configs (profile_id, game_folder, slot_idx, bot_name, ai_level) +VALUES (?, ?, ?, ?, ?) +ON CONFLICT(profile_id, game_folder, slot_idx) DO UPDATE SET + bot_name = excluded.bot_name, + ai_level = excluded.ai_level; +""" + +# --- Statistics --- +STATS_SQL = { + "profile": { + "select_one": """ + SELECT games_played, games_won, games_lost, current_streak, + longest_streak, best_time_sec, total_time_sec + FROM player_stats WHERE profile_id = ? AND variant_id = ?; + """, + "insert": """ + INSERT INTO player_stats ( + profile_id, variant_id, games_played, games_won, games_lost, + current_streak, longest_streak, best_time_sec, total_time_sec + ) VALUES (?, ?, 1, ?, ?, ?, ?, ?, ?); + """, + "update": """ + UPDATE player_stats SET + games_played = ?, games_won = ?, games_lost = ?, + current_streak = ?, longest_streak = ?, + best_time_sec = ?, total_time_sec = ? + WHERE profile_id = ? AND variant_id = ?; + """, + "aggregate_folder": """ + SELECT COALESCE(SUM(ps.games_played), 0) AS played, + COALESCE(SUM(ps.games_won), 0) AS won, + COALESCE(SUM(ps.games_lost), 0) AS lost, + COALESCE(SUM(ps.current_streak), 0) AS c_streak, + COALESCE(MAX(ps.longest_streak), 0) AS l_streak, + MIN(ps.best_time_sec) AS best_time, + COALESCE(SUM(ps.total_time_sec), 0.0) AS total_time + FROM player_stats ps + JOIN core.game_variants gv ON gv.id = ps.variant_id + WHERE ps.profile_id = ? AND gv.folder_path = ?; + """, + "aggregate_all": """ + SELECT COALESCE(SUM(games_played), 0) AS played, + COALESCE(SUM(games_won), 0) AS won, + COALESCE(SUM(games_lost), 0) AS lost, + COALESCE(SUM(current_streak), 0) AS c_streak, + COALESCE(MAX(longest_streak), 0) AS l_streak, + MIN(best_time_sec) AS best_time, + COALESCE(SUM(total_time_sec), 0.0) AS total_time + FROM player_stats WHERE profile_id = ?; + """, + }, + "bj_account": { + "select_one": """ + SELECT games_played, games_won, games_lost, current_streak, + longest_streak, best_time_sec, total_time_sec + FROM blackjack_account_stats WHERE bj_account_id = ? AND variant_id = ?; + """, + "insert": """ + INSERT INTO blackjack_account_stats ( + bj_account_id, variant_id, games_played, games_won, games_lost, + current_streak, longest_streak, best_time_sec, total_time_sec + ) VALUES (?, ?, 1, ?, ?, ?, ?, ?, ?); + """, + "update": """ + UPDATE blackjack_account_stats SET + games_played = ?, games_won = ?, games_lost = ?, + current_streak = ?, longest_streak = ?, + best_time_sec = ?, total_time_sec = ? + WHERE bj_account_id = ? AND variant_id = ?; + """, + "aggregate_folder": """ + SELECT COALESCE(SUM(bs.games_played), 0) AS played, + COALESCE(SUM(bs.games_won), 0) AS won, + COALESCE(SUM(bs.games_lost), 0) AS lost, + COALESCE(SUM(bs.current_streak), 0) AS c_streak, + COALESCE(MAX(bs.longest_streak), 0) AS l_streak, + MIN(bs.best_time_sec) AS best_time, + COALESCE(SUM(bs.total_time_sec), 0.0) AS total_time + FROM blackjack_account_stats bs + JOIN core.game_variants gv ON gv.id = bs.variant_id + WHERE bs.bj_account_id = ? AND gv.folder_path = ?; + """, + "aggregate_all": """ + SELECT COALESCE(SUM(games_played), 0) AS played, + COALESCE(SUM(games_won), 0) AS won, + COALESCE(SUM(games_lost), 0) AS lost, + COALESCE(SUM(current_streak), 0) AS c_streak, + COALESCE(MAX(longest_streak), 0) AS l_streak, + MIN(best_time_sec) AS best_time, + COALESCE(SUM(total_time_sec), 0.0) AS total_time + FROM blackjack_account_stats WHERE bj_account_id = ?; + """, + }, +} \ No newline at end of file diff --git a/resources/images/background.jpeg b/resources/images/background.jpeg new file mode 100644 index 0000000..5a5468c Binary files /dev/null and b/resources/images/background.jpeg differ diff --git a/resources/images/button1.png b/resources/images/button1.png new file mode 100644 index 0000000..30743d4 Binary files /dev/null and b/resources/images/button1.png differ diff --git a/resources/images/button1_active.png b/resources/images/button1_active.png new file mode 100644 index 0000000..51ed4d0 Binary files /dev/null and b/resources/images/button1_active.png differ diff --git a/resources/images/cards/default/Back_Black.png b/resources/images/cards/default/Back_Black.png new file mode 100644 index 0000000..247e250 Binary files /dev/null and b/resources/images/cards/default/Back_Black.png differ diff --git a/resources/images/cards/default/Back_Blue.png b/resources/images/cards/default/Back_Blue.png new file mode 100644 index 0000000..2be857b Binary files /dev/null and b/resources/images/cards/default/Back_Blue.png differ diff --git a/resources/images/cards/default/Back_Red.png b/resources/images/cards/default/Back_Red.png new file mode 100644 index 0000000..9904bc9 Binary files /dev/null and b/resources/images/cards/default/Back_Red.png differ diff --git a/resources/images/cards/default/C10.png b/resources/images/cards/default/C10.png new file mode 100644 index 0000000..db7ee5a Binary files /dev/null and b/resources/images/cards/default/C10.png differ diff --git a/resources/images/cards/default/C2.png b/resources/images/cards/default/C2.png new file mode 100644 index 0000000..20f4036 Binary files /dev/null and b/resources/images/cards/default/C2.png differ diff --git a/resources/images/cards/default/C3.png b/resources/images/cards/default/C3.png new file mode 100644 index 0000000..9ff9041 Binary files /dev/null and b/resources/images/cards/default/C3.png differ diff --git a/resources/images/cards/default/C4.png b/resources/images/cards/default/C4.png new file mode 100644 index 0000000..c9ff1e5 Binary files /dev/null and b/resources/images/cards/default/C4.png differ diff --git a/resources/images/cards/default/C5.png b/resources/images/cards/default/C5.png new file mode 100644 index 0000000..389276a Binary files /dev/null and b/resources/images/cards/default/C5.png differ diff --git a/resources/images/cards/default/C6.png b/resources/images/cards/default/C6.png new file mode 100644 index 0000000..6aa66f5 Binary files /dev/null and b/resources/images/cards/default/C6.png differ diff --git a/resources/images/cards/default/C7.png b/resources/images/cards/default/C7.png new file mode 100644 index 0000000..b16460a Binary files /dev/null and b/resources/images/cards/default/C7.png differ diff --git a/resources/images/cards/default/C8.png b/resources/images/cards/default/C8.png new file mode 100644 index 0000000..3ed45aa Binary files /dev/null and b/resources/images/cards/default/C8.png differ diff --git a/resources/images/cards/default/C9.png b/resources/images/cards/default/C9.png new file mode 100644 index 0000000..1249a49 Binary files /dev/null and b/resources/images/cards/default/C9.png differ diff --git a/resources/images/cards/default/CA.png b/resources/images/cards/default/CA.png new file mode 100644 index 0000000..ba2c0ca Binary files /dev/null and b/resources/images/cards/default/CA.png differ diff --git a/resources/images/cards/default/CJ.png b/resources/images/cards/default/CJ.png new file mode 100644 index 0000000..f7ccc4e Binary files /dev/null and b/resources/images/cards/default/CJ.png differ diff --git a/resources/images/cards/default/CK.png b/resources/images/cards/default/CK.png new file mode 100644 index 0000000..a60a404 Binary files /dev/null and b/resources/images/cards/default/CK.png differ diff --git a/resources/images/cards/default/CQ.png b/resources/images/cards/default/CQ.png new file mode 100644 index 0000000..3632dd9 Binary files /dev/null and b/resources/images/cards/default/CQ.png differ diff --git a/resources/images/cards/default/D10.png b/resources/images/cards/default/D10.png new file mode 100644 index 0000000..d2dd495 Binary files /dev/null and b/resources/images/cards/default/D10.png differ diff --git a/resources/images/cards/default/D2.png b/resources/images/cards/default/D2.png new file mode 100644 index 0000000..9337296 Binary files /dev/null and b/resources/images/cards/default/D2.png differ diff --git a/resources/images/cards/default/D3.png b/resources/images/cards/default/D3.png new file mode 100644 index 0000000..0e30432 Binary files /dev/null and b/resources/images/cards/default/D3.png differ diff --git a/resources/images/cards/default/D4.png b/resources/images/cards/default/D4.png new file mode 100644 index 0000000..4449011 Binary files /dev/null and b/resources/images/cards/default/D4.png differ diff --git a/resources/images/cards/default/D5.png b/resources/images/cards/default/D5.png new file mode 100644 index 0000000..1be1d2e Binary files /dev/null and b/resources/images/cards/default/D5.png differ diff --git a/resources/images/cards/default/D6.png b/resources/images/cards/default/D6.png new file mode 100644 index 0000000..2451ff0 Binary files /dev/null and b/resources/images/cards/default/D6.png differ diff --git a/resources/images/cards/default/D7.png b/resources/images/cards/default/D7.png new file mode 100644 index 0000000..319ed9f Binary files /dev/null and b/resources/images/cards/default/D7.png differ diff --git a/resources/images/cards/default/D8.png b/resources/images/cards/default/D8.png new file mode 100644 index 0000000..c57ca52 Binary files /dev/null and b/resources/images/cards/default/D8.png differ diff --git a/resources/images/cards/default/D9.png b/resources/images/cards/default/D9.png new file mode 100644 index 0000000..368986a Binary files /dev/null and b/resources/images/cards/default/D9.png differ diff --git a/resources/images/cards/default/DA.png b/resources/images/cards/default/DA.png new file mode 100644 index 0000000..9b93445 Binary files /dev/null and b/resources/images/cards/default/DA.png differ diff --git a/resources/images/cards/default/DJ.png b/resources/images/cards/default/DJ.png new file mode 100644 index 0000000..d46c0c5 Binary files /dev/null and b/resources/images/cards/default/DJ.png differ diff --git a/resources/images/cards/default/DK.png b/resources/images/cards/default/DK.png new file mode 100644 index 0000000..7c3d0ce Binary files /dev/null and b/resources/images/cards/default/DK.png differ diff --git a/resources/images/cards/default/DQ.png b/resources/images/cards/default/DQ.png new file mode 100644 index 0000000..823720f Binary files /dev/null and b/resources/images/cards/default/DQ.png differ diff --git a/resources/images/cards/default/H10.png b/resources/images/cards/default/H10.png new file mode 100644 index 0000000..f7c7d92 Binary files /dev/null and b/resources/images/cards/default/H10.png differ diff --git a/resources/images/cards/default/H2.png b/resources/images/cards/default/H2.png new file mode 100644 index 0000000..d33b02c Binary files /dev/null and b/resources/images/cards/default/H2.png differ diff --git a/resources/images/cards/default/H3.png b/resources/images/cards/default/H3.png new file mode 100644 index 0000000..32feb92 Binary files /dev/null and b/resources/images/cards/default/H3.png differ diff --git a/resources/images/cards/default/H4.png b/resources/images/cards/default/H4.png new file mode 100644 index 0000000..ecd77d4 Binary files /dev/null and b/resources/images/cards/default/H4.png differ diff --git a/resources/images/cards/default/H5.png b/resources/images/cards/default/H5.png new file mode 100644 index 0000000..4faf812 Binary files /dev/null and b/resources/images/cards/default/H5.png differ diff --git a/resources/images/cards/default/H6.png b/resources/images/cards/default/H6.png new file mode 100644 index 0000000..b4b5e4a Binary files /dev/null and b/resources/images/cards/default/H6.png differ diff --git a/resources/images/cards/default/H7.png b/resources/images/cards/default/H7.png new file mode 100644 index 0000000..fd4f31a Binary files /dev/null and b/resources/images/cards/default/H7.png differ diff --git a/resources/images/cards/default/H8.png b/resources/images/cards/default/H8.png new file mode 100644 index 0000000..f219780 Binary files /dev/null and b/resources/images/cards/default/H8.png differ diff --git a/resources/images/cards/default/H9.png b/resources/images/cards/default/H9.png new file mode 100644 index 0000000..069598b Binary files /dev/null and b/resources/images/cards/default/H9.png differ diff --git a/resources/images/cards/default/HA.png b/resources/images/cards/default/HA.png new file mode 100644 index 0000000..07ba328 Binary files /dev/null and b/resources/images/cards/default/HA.png differ diff --git a/resources/images/cards/default/HJ.png b/resources/images/cards/default/HJ.png new file mode 100644 index 0000000..aa753c8 Binary files /dev/null and b/resources/images/cards/default/HJ.png differ diff --git a/resources/images/cards/default/HK.png b/resources/images/cards/default/HK.png new file mode 100644 index 0000000..6e9aee4 Binary files /dev/null and b/resources/images/cards/default/HK.png differ diff --git a/resources/images/cards/default/HQ.png b/resources/images/cards/default/HQ.png new file mode 100644 index 0000000..91cb91d Binary files /dev/null and b/resources/images/cards/default/HQ.png differ diff --git a/resources/images/cards/default/Joker.png b/resources/images/cards/default/Joker.png new file mode 100644 index 0000000..dccbd70 Binary files /dev/null and b/resources/images/cards/default/Joker.png differ diff --git a/resources/images/cards/default/Joker2.png b/resources/images/cards/default/Joker2.png new file mode 100644 index 0000000..1e7b892 Binary files /dev/null and b/resources/images/cards/default/Joker2.png differ diff --git a/resources/images/cards/default/S10.png b/resources/images/cards/default/S10.png new file mode 100644 index 0000000..5f297f9 Binary files /dev/null and b/resources/images/cards/default/S10.png differ diff --git a/resources/images/cards/default/S2.png b/resources/images/cards/default/S2.png new file mode 100644 index 0000000..28337ea Binary files /dev/null and b/resources/images/cards/default/S2.png differ diff --git a/resources/images/cards/default/S3.png b/resources/images/cards/default/S3.png new file mode 100644 index 0000000..88ce101 Binary files /dev/null and b/resources/images/cards/default/S3.png differ diff --git a/resources/images/cards/default/S4.png b/resources/images/cards/default/S4.png new file mode 100644 index 0000000..388d0a3 Binary files /dev/null and b/resources/images/cards/default/S4.png differ diff --git a/resources/images/cards/default/S5.png b/resources/images/cards/default/S5.png new file mode 100644 index 0000000..63fc2b1 Binary files /dev/null and b/resources/images/cards/default/S5.png differ diff --git a/resources/images/cards/default/S6.png b/resources/images/cards/default/S6.png new file mode 100644 index 0000000..28de5ac Binary files /dev/null and b/resources/images/cards/default/S6.png differ diff --git a/resources/images/cards/default/S7.png b/resources/images/cards/default/S7.png new file mode 100644 index 0000000..a67940a Binary files /dev/null and b/resources/images/cards/default/S7.png differ diff --git a/resources/images/cards/default/S8.png b/resources/images/cards/default/S8.png new file mode 100644 index 0000000..40c82be Binary files /dev/null and b/resources/images/cards/default/S8.png differ diff --git a/resources/images/cards/default/S9.png b/resources/images/cards/default/S9.png new file mode 100644 index 0000000..f95a9fc Binary files /dev/null and b/resources/images/cards/default/S9.png differ diff --git a/resources/images/cards/default/SA.png b/resources/images/cards/default/SA.png new file mode 100644 index 0000000..d11e93d Binary files /dev/null and b/resources/images/cards/default/SA.png differ diff --git a/resources/images/cards/default/SJ.png b/resources/images/cards/default/SJ.png new file mode 100644 index 0000000..bc0b719 Binary files /dev/null and b/resources/images/cards/default/SJ.png differ diff --git a/resources/images/cards/default/SK.png b/resources/images/cards/default/SK.png new file mode 100644 index 0000000..a9b24b4 Binary files /dev/null and b/resources/images/cards/default/SK.png differ diff --git a/resources/images/cards/default/SQ.png b/resources/images/cards/default/SQ.png new file mode 100644 index 0000000..1773f29 Binary files /dev/null and b/resources/images/cards/default/SQ.png differ diff --git a/resources/images/chat_window.png b/resources/images/chat_window.png new file mode 100644 index 0000000..50c46ff Binary files /dev/null and b/resources/images/chat_window.png differ diff --git a/resources/images/lose.gif b/resources/images/lose.gif new file mode 100644 index 0000000..f55ba9f Binary files /dev/null and b/resources/images/lose.gif differ diff --git a/resources/images/selection_active.png b/resources/images/selection_active.png new file mode 100644 index 0000000..c34a05a Binary files /dev/null and b/resources/images/selection_active.png differ diff --git a/resources/images/selection_inactive.png b/resources/images/selection_inactive.png new file mode 100644 index 0000000..b35a7b5 Binary files /dev/null and b/resources/images/selection_inactive.png differ diff --git a/resources/images/title1.png b/resources/images/title1.png new file mode 100644 index 0000000..3280113 Binary files /dev/null and b/resources/images/title1.png differ diff --git a/resources/images/win.gif b/resources/images/win.gif new file mode 100644 index 0000000..592a543 Binary files /dev/null and b/resources/images/win.gif differ diff --git a/resources/sounds/ambiance/Beyond_The_Iron_Gate.mp3 b/resources/sounds/ambiance/Beyond_The_Iron_Gate.mp3 new file mode 100644 index 0000000..f22d1c3 Binary files /dev/null and b/resources/sounds/ambiance/Beyond_The_Iron_Gate.mp3 differ diff --git a/resources/sounds/ambiance/The_Midnight_Hand.mp3 b/resources/sounds/ambiance/The_Midnight_Hand.mp3 new file mode 100644 index 0000000..82543e7 Binary files /dev/null and b/resources/sounds/ambiance/The_Midnight_Hand.mp3 differ diff --git a/resources/sounds/ambiance/owl-city-stand-sfx.mp3 b/resources/sounds/ambiance/owl-city-stand-sfx.mp3 new file mode 100644 index 0000000..5ae513d Binary files /dev/null and b/resources/sounds/ambiance/owl-city-stand-sfx.mp3 differ diff --git a/resources/sounds/menu_effects/click.ogg b/resources/sounds/menu_effects/click.ogg new file mode 100644 index 0000000..62de5e4 Binary files /dev/null and b/resources/sounds/menu_effects/click.ogg differ diff --git a/resources/sounds/menu_effects/end-battle.mp3 b/resources/sounds/menu_effects/end-battle.mp3 new file mode 100644 index 0000000..e2e367d Binary files /dev/null and b/resources/sounds/menu_effects/end-battle.mp3 differ diff --git a/resources/sounds/menu_effects/failure.mp3 b/resources/sounds/menu_effects/failure.mp3 new file mode 100644 index 0000000..2bcc9a8 Binary files /dev/null and b/resources/sounds/menu_effects/failure.mp3 differ diff --git a/resources/sounds/menu_effects/roll-for-initiative.mp3 b/resources/sounds/menu_effects/roll-for-initiative.mp3 new file mode 100644 index 0000000..e77c146 Binary files /dev/null and b/resources/sounds/menu_effects/roll-for-initiative.mp3 differ diff --git a/resources/sounds/menu_effects/success.mp3 b/resources/sounds/menu_effects/success.mp3 new file mode 100644 index 0000000..50e0c3e Binary files /dev/null and b/resources/sounds/menu_effects/success.mp3 differ diff --git a/user_data.db b/user_data.db new file mode 100644 index 0000000..85ad287 Binary files /dev/null and b/user_data.db differ diff --git a/view/__pycache__/assets_manager.cpython-311.pyc b/view/__pycache__/assets_manager.cpython-311.pyc new file mode 100644 index 0000000..9d54e49 Binary files /dev/null and b/view/__pycache__/assets_manager.cpython-311.pyc differ diff --git a/view/__pycache__/main_window.cpython-311.pyc b/view/__pycache__/main_window.cpython-311.pyc new file mode 100644 index 0000000..f4f83e4 Binary files /dev/null and b/view/__pycache__/main_window.cpython-311.pyc differ diff --git a/view/assets_manager.py b/view/assets_manager.py new file mode 100644 index 0000000..a000117 --- /dev/null +++ b/view/assets_manager.py @@ -0,0 +1,72 @@ +# -*- coding: utf-8 -*- +from pathlib import Path +from PIL import Image, ImageTk +from models.resource_manager import ResourceManager +from resources.code_res.game_constants import OUTCOME_GIF_SIZE, PLAYING_CARD_SIZE + + +class AssetManager: + def __init__(self, root_dir: Path): + self.res = ResourceManager(root_dir) + self.raw_bg = self._load_pil(self.res.get_ui_image_path("background")) + self.raw_title = self._load_pil(self.res.get_ui_image_path("title")) + self.raw_btn = self._load_pil(self.res.get_ui_image_path("btn_normal")) + self.raw_btn_active = self._load_pil(self.res.get_ui_image_path("btn_active")) + self.raw_sel = self._load_pil(self.res.get_ui_image_path("sel_inactive")) + self.raw_sel_active = self._load_pil(self.res.get_ui_image_path("sel_active")) + self.raw_chat_frame = self._load_pil(self.res.get_ui_image_path("card_frame")) + self._tk_cache = {} + + @staticmethod + def _load_pil(path: Path): + if path.is_file(): + try: + return Image.open(path).convert("RGBA") + except Exception: + return None + return None + + def get_card_photo(self, card_filename: str, size=PLAYING_CARD_SIZE) -> ImageTk.PhotoImage | None: + key = ("card", self.res.card_theme, card_filename, size) + if key not in self._tk_cache: + pil = self._load_pil(self.res.get_card_path(card_filename)) + if pil: + self._tk_cache[key] = ImageTk.PhotoImage(pil.resize(size, Image.Resampling.LANCZOS)) + return self._tk_cache.get(key) + + def get_card_back_photo(self, color: str = "Black", size=PLAYING_CARD_SIZE) -> ImageTk.PhotoImage | None: + key = ("card_back", self.res.card_theme, color, size) + if key not in self._tk_cache: + pil = self._load_pil(self.res.get_card_back_path(color)) + if pil: + self._tk_cache[key] = ImageTk.PhotoImage(pil.resize(size, Image.Resampling.LANCZOS)) + return self._tk_cache.get(key) + + def get_scaled_photo(self, name: str, pil_img, size: tuple[int, int]): + if not pil_img: + return None + key = (name, size) + if key not in self._tk_cache: + self._tk_cache[key] = ImageTk.PhotoImage(pil_img.resize(size, Image.Resampling.LANCZOS)) + return self._tk_cache[key] + + def get_gif_frames(self, key_or_filename: str, size=OUTCOME_GIF_SIZE) -> list[ImageTk.PhotoImage]: + cache_key = ("gif", key_or_filename, size) + if cache_key not in self._tk_cache: + frames = [] + path = self.res.get_ui_image_path(key_or_filename) + if path.is_file(): + try: + with Image.open(path) as gif: + idx = 0 + while True: + frame = gif.copy().convert("RGBA").resize(size, Image.Resampling.LANCZOS) + frames.append(ImageTk.PhotoImage(frame)) + idx += 1 + gif.seek(idx) + except EOFError: + pass + except Exception: + pass + self._tk_cache[cache_key] = frames + return self._tk_cache[cache_key] \ No newline at end of file diff --git a/view/dialogs/__pycache__/audio_settings_dialog.cpython-311.pyc b/view/dialogs/__pycache__/audio_settings_dialog.cpython-311.pyc new file mode 100644 index 0000000..76e5071 Binary files /dev/null and b/view/dialogs/__pycache__/audio_settings_dialog.cpython-311.pyc differ diff --git a/view/dialogs/audio_settings_dialog.py b/view/dialogs/audio_settings_dialog.py new file mode 100644 index 0000000..ca814fb --- /dev/null +++ b/view/dialogs/audio_settings_dialog.py @@ -0,0 +1,89 @@ +# -*- coding: utf-8 -*- +import tkinter as tk +from resources.code_res.game_constants import ( + ACCENT_GOLD, ACCENT_GOTH, BG_COLOR, FG_COLOR, + MODAL_BG, MUTED_FG, PANEL_BG, SUBTLE_BORDER +) +from resources.code_res.i18n import t +from view.widgets.image_button import ImageButton + + +class AudioSettingsDialog(tk.Frame): + @classmethod + def open(cls, root_window: tk.Tk, assets, sound_mgr): + existing = getattr(root_window, "_audio_overlay", None) + if existing and existing.winfo_exists(): + existing.lift() + return existing + dlg = cls(root_window, assets, sound_mgr) + root_window._audio_overlay = dlg + return dlg + + def __init__(self, root_window: tk.Tk, assets, sound_mgr): + super().__init__( + root_window, bg=MODAL_BG, highlightthickness=2, + highlightbackground=ACCENT_GOTH, padx=30, pady=24 + ) + self.root_window = root_window + self.assets = assets + self.sound_mgr = sound_mgr + self.place(relx=0.5, rely=0.5, anchor="center") + self._build() + + def _build(self): + tk.Label(self, text=t("audio_title"), font=("Georgia", 17, "bold"), fg=ACCENT_GOTH, bg=MODAL_BG).pack(pady=(0, 6)) + tk.Label(self, text=t("audio_subtitle"), font=("Helvetica", 9), fg=MUTED_FG, bg=MODAL_BG).pack(pady=(0, 18)) + + self._build_slider_row( + label_txt=t("audio_ambiance_label"), + desc_txt=t("audio_ambiance_desc"), + initial_vol=self.sound_mgr.ambiance_volume, + on_change=lambda v: self.sound_mgr.set_ambiance_volume(v, persist=True), + ) + self._build_slider_row( + label_txt=t("audio_sfx_label"), + desc_txt=t("audio_sfx_desc"), + initial_vol=self.sound_mgr.menu_volume, + on_change=lambda v: self.sound_mgr.set_menu_volume(v, persist=True), + ) + + btn_row = tk.Frame(self, bg=MODAL_BG) + btn_row.pack(fill="x", pady=(16, 0)) + + ImageButton( + btn_row, t("audio_test_btn"), self.assets.raw_sel, self.assets.raw_sel_active, + lambda: self.sound_mgr.play("deal"), sound_mgr=None, width=150, height=38, font=("Helvetica", 10, "bold") + ).pack(side="left") + + ImageButton( + btn_row, t("audio_done_btn"), self.assets.raw_btn, self.assets.raw_btn_active, + self.close, sound_mgr=self.sound_mgr, width=150, height=38, font=("Helvetica", 10, "bold") + ).pack(side="right") + + def _build_slider_row(self, label_txt: str, desc_txt: str, initial_vol: float, on_change): + row = tk.Frame(self, bg=PANEL_BG, padx=16, pady=12, highlightthickness=1, highlightbackground=SUBTLE_BORDER) + row.pack(fill="x", pady=6) + + top = tk.Frame(row, bg=PANEL_BG) + top.pack(fill="x") + tk.Label(top, text=label_txt, font=("Helvetica", 11, "bold"), fg=FG_COLOR, bg=PANEL_BG).pack(side="left") + pct_lbl = tk.Label(top, text=f"{int(round(initial_vol * 100))} %", font=("Helvetica", 11, "bold"), fg=ACCENT_GOLD, bg=PANEL_BG) + pct_lbl.pack(side="right") + + tk.Label(row, text=desc_txt, font=("Helvetica", 8), fg=MUTED_FG, bg=PANEL_BG).pack(anchor="w", pady=(2, 6)) + + def _handle(val_str): + pct_lbl.configure(text=f"{int(round(float(val_str)))} %") + on_change(float(val_str) / 100.0) + + scale = tk.Scale( + row, from_=0, to=100, orient="horizontal", showvalue=False, + length=360, bg=PANEL_BG, fg=FG_COLOR, troughcolor=BG_COLOR, + activebackground=ACCENT_GOTH, highlightthickness=0, bd=0, command=_handle + ) + scale.set(int(round(initial_vol * 100))) + scale.pack(fill="x") + + def close(self): + self.destroy() + self.root_window._audio_overlay = None \ No newline at end of file diff --git a/view/main_window.py b/view/main_window.py new file mode 100644 index 0000000..298af45 --- /dev/null +++ b/view/main_window.py @@ -0,0 +1,134 @@ +# -*- coding: utf-8 -*- +# view/main_window.py +import sys +import tkinter as tk +from tkinter import ttk +from pathlib import Path + +from models.database import Database +from resources.code_res.game_constants import ( + ACCENT_GOTH, BG_COLOR, BORDER_COLOR, DEFAULT_WINDOW_GEOM, + FG_COLOR, INPUT_BG, MIN_WINDOW_SIZE, PANEL_BG, SUBTLE_BORDER +) +from resources.code_res.i18n import t +from view.assets_manager import AssetManager +from view.menus.login_view import LoginView +from view.menus.main_menu_view import MainMenuView +from view.menus.statistics_view import StatisticsView +from view.widgets.resizing_bg import ResizingBG + + +class GothCardCollectionView(tk.Tk): + def __init__(self, ctrl, root_dir: Path): + super().__init__() + self.ctrl = ctrl + self.title(t("app_title")) + self.configure(bg=BG_COLOR) + self.minsize(*MIN_WINDOW_SIZE) + + self._restore_window_geometry() + self._setup_global_ttk_styles() + + self._geom_save_job = None + self.bind("", self._on_window_configure) + self.protocol("WM_DELETE_WINDOW", self.close_app) + + self.assets = AssetManager(root_dir) + self.bg_widget = None + self.login_view = LoginView(self) + self.main_menu_view = MainMenuView(self) + self.statistics_view = StatisticsView(self) + + def _setup_global_ttk_styles(self): + style = ttk.Style() + style.theme_use("clam") + style.configure( + "Goth.TCombobox", + fieldbackground=INPUT_BG, + background=PANEL_BG, + foreground=FG_COLOR, + darkcolor=INPUT_BG, + lightcolor=INPUT_BG, + bordercolor=BORDER_COLOR, + arrowcolor=ACCENT_GOTH, + ) + style.map( + "Goth.TCombobox", + fieldbackground=[("readonly", INPUT_BG)], + foreground=[("readonly", FG_COLOR)], + ) + style.configure( + "Goth.Horizontal.TProgressbar", + troughcolor=BG_COLOR, + background=ACCENT_GOTH, + bordercolor=SUBTLE_BORDER, + lightcolor=ACCENT_GOTH, + darkcolor=ACCENT_GOTH, + ) + + def _restore_window_geometry(self): + saved_geom = Database.load_setting("window_geometry", DEFAULT_WINDOW_GEOM) + saved_zoom = Database.load_setting("window_zoomed", "0") + try: + self.geometry(saved_geom) + if saved_zoom == "1": + if sys.platform == "darwin": + self.geometry(f"{self.winfo_screenwidth()}x{self.winfo_screenheight()}+0+0") + else: + try: + self.attributes("-zoomed", True) + except Exception: + self.state("zoomed") + except Exception: + self.geometry(DEFAULT_WINDOW_GEOM) + + def _on_window_configure(self, event): + if event.widget == self: + if self._geom_save_job: + self.after_cancel(self._geom_save_job) + self._geom_save_job = self.after(400, self._save_window_state) + + def _save_window_state(self): + try: + is_zoomed = False + if sys.platform == "darwin": + is_zoomed = ( + self.winfo_width() >= self.winfo_screenwidth() - 20 + and self.winfo_height() >= self.winfo_screenheight() - 80 + ) + else: + try: + is_zoomed = bool(self.attributes("-zoomed")) + except Exception: + is_zoomed = (self.state() == "zoomed") + + Database.save_setting("window_zoomed", "1" if is_zoomed else "0") + min_w, min_h = MIN_WINDOW_SIZE + if not is_zoomed and self.winfo_width() >= min_w and self.winfo_height() >= min_h: + Database.save_setting( + "window_geometry", + f"{self.winfo_width()}x{self.winfo_height()}+{self.winfo_x()}+{self.winfo_y()}" + ) + except Exception: + pass + + def close_app(self): + self._save_window_state() + Database.close() + self.destroy() + + def clear_window(self, apply_global_bg=True): + for widget in self.winfo_children(): + widget.destroy() + if apply_global_bg and self.assets.raw_bg: + self.bg_widget = ResizingBG(self, self.assets.raw_bg, bg=BG_COLOR) + self.bg_widget.place(relx=0, rely=0, relwidth=1, relheight=1) + + def show_login(self, profiles: list[str], preselect_name: str = ""): + self.login_view.show(profiles, preselect_name) + + def show_main_menu(self, profile: dict, available_games: list[dict], devils_resume_only: bool = False): + self.main_menu_view.show(profile, available_games, devils_resume_only=devils_resume_only) + + def show_statistics(self, profile: dict): + self.statistics_view.show(profile) \ No newline at end of file diff --git a/view/menu_views.py b/view/menu_views.py new file mode 100644 index 0000000..1f2f9ec --- /dev/null +++ b/view/menu_views.py @@ -0,0 +1,219 @@ +# -*- coding: utf-8 -*- +# view/menu_views.py +import tkinter as tk +from tkinter import ttk +from PIL import Image, ImageEnhance, ImageTk + +from models.database import Database +from resources.code_res.game_constants import ( + ACCENT_GOLD, ACCENT_GOTH, BG_COLOR, BORDER_COLOR, FG_COLOR, + INPUT_BG, MENU_CARD_SIZE, MUTED_FG, PANEL_BG, SUBTLE_BORDER +) +from resources.code_res.i18n import t +from view.assets_manager import StatsBoardWidget, create_img_button, show_audio_settings_overlay + + +class MenuViews: + def __init__(self, root_view): + self.root = root_view + self.ctrl = root_view.ctrl + self.assets = root_view.assets + self.sounds = root_view.ctrl.sounds + + self.profile_var = None + self.new_name_var = None + self._card_refs = [] + self._setup_styles() + + def _setup_styles(self): + style = ttk.Style() + style.theme_use("clam") + style.configure( + "Goth.TCombobox", + fieldbackground=INPUT_BG, + background=PANEL_BG, + foreground=FG_COLOR, + darkcolor=INPUT_BG, + lightcolor=INPUT_BG, + bordercolor=BORDER_COLOR, + arrowcolor=ACCENT_GOTH, + ) + style.map( + "Goth.TCombobox", + fieldbackground=[("readonly", INPUT_BG)], + foreground=[("readonly", FG_COLOR)], + ) + style.configure( + "Goth.Horizontal.TProgressbar", + troughcolor=BG_COLOR, + background=ACCENT_GOTH, + bordercolor=SUBTLE_BORDER, + lightcolor=ACCENT_GOTH, + darkcolor=ACCENT_GOTH, + ) + + def show_login(self, profiles: list[str], preselect_name: str = ""): + self.root.clear_window(apply_global_bg=True) + self._card_refs.clear() + + top_controls = tk.Frame(self.root, bg=BG_COLOR) + top_controls.place(relx=0.97, rely=0.04, anchor="ne") + + create_img_button( + top_controls, t("btn_lang"), self.assets.raw_sel, self.assets.raw_sel_active, + lambda: self.ctrl.toggle_language(), sound_mgr=self.sounds, width=85, height=36, font=("Helvetica", 10, "bold") + ).pack(side="left", padx=(0, 8)) + + create_img_button( + top_controls, t("btn_audio"), self.assets.raw_sel, self.assets.raw_sel_active, + lambda: show_audio_settings_overlay(self.root, self.assets, self.sounds), + sound_mgr=self.sounds, width=105, height=36, font=("Helvetica", 10, "bold") + ).pack(side="left") + + main_frame = tk.Frame(self.root, bg=BG_COLOR, padx=35, pady=30, highlightthickness=1, highlightbackground=SUBTLE_BORDER) + main_frame.place(relx=0.5, rely=0.5, anchor="center") + + title_photo = self.assets.get_scaled_photo("title_login", self.assets.raw_title, (360, 90)) + if title_photo: + tk.Label(main_frame, image=title_photo, bg=BG_COLOR, bd=0).pack(pady=(0, 15)) + else: + tk.Label(main_frame, text=t("app_title").upper(), font=("Georgia", 22, "bold"), fg=ACCENT_GOTH, bg=BG_COLOR).pack(pady=(0, 15)) + + if profiles: + frame = tk.Frame(main_frame, bg=BG_COLOR) + frame.pack(pady=10) + initial_prof = preselect_name if preselect_name in profiles else profiles[0] + self.profile_var = tk.StringVar(value=initial_prof) + cb = ttk.Combobox( + frame, textvariable=self.profile_var, values=profiles, + state="readonly", font=("Helvetica", 12), width=18, style="Goth.TCombobox" + ) + cb.grid(row=0, column=0, padx=10) + create_img_button( + frame, t("login_btn"), self.assets.raw_btn, self.assets.raw_btn_active, + lambda: self.ctrl.do_login(self.profile_var.get()), sound_mgr=self.sounds, width=155 + ).grid(row=0, column=1) + + tk.Frame(main_frame, bg=SUBTLE_BORDER, height=1).pack(fill="x", padx=20, pady=15) + + new_frame = tk.Frame(main_frame, bg=BG_COLOR) + new_frame.pack(pady=8) + self.new_name_var = tk.StringVar() + entry = tk.Entry( + new_frame, textvariable=self.new_name_var, font=("Helvetica", 13), + bg=INPUT_BG, fg=FG_COLOR, bd=0, width=19, + highlightthickness=1, highlightbackground=BORDER_COLOR, insertbackground="white" + ) + entry.grid(row=0, column=0, padx=10, ipady=6) + entry.bind("", lambda e: self.ctrl.do_create_profile(self.new_name_var.get().strip())) + + create_img_button( + new_frame, t("new_profile_btn"), self.assets.raw_btn, self.assets.raw_btn_active, + lambda: self.ctrl.do_create_profile(self.new_name_var.get().strip()), sound_mgr=self.sounds, width=155 + ).grid(row=0, column=1) + + def show_main_menu(self, profile: dict, available_games: list[dict]): + self.root.clear_window(apply_global_bg=True) + self._card_refs.clear() + + container = tk.Frame(self.root, bg=BG_COLOR, padx=24, pady=16) + container.place(relx=0.5, rely=0.5, anchor="center", relwidth=0.93, relheight=0.93) + + top_bar = tk.Frame(container, bg=BG_COLOR) + top_bar.pack(fill="x", pady=(0, 8)) + + left_btns = tk.Frame(top_bar, bg=BG_COLOR) + left_btns.pack(side="left") + + create_img_button( + left_btns, t("btn_switch_profile"), self.assets.raw_sel, self.assets.raw_sel_active, + self.ctrl.logout_to_login, sound_mgr=self.sounds, width=155, height=38, font=("Helvetica", 10, "bold") + ).pack(side="left", padx=(0, 6)) + + create_img_button( + left_btns, t("btn_lang"), self.assets.raw_sel, self.assets.raw_sel_active, + lambda: self.ctrl.toggle_language(), sound_mgr=self.sounds, width=82, height=38, font=("Helvetica", 10, "bold") + ).pack(side="left", padx=(0, 6)) + + create_img_button( + left_btns, t("btn_audio"), self.assets.raw_sel, self.assets.raw_sel_active, + lambda: show_audio_settings_overlay(self.root, self.assets, self.sounds), + sound_mgr=self.sounds, width=100, height=38, font=("Helvetica", 10, "bold") + ).pack(side="left") + + tk.Label(top_bar, text=t("header_title"), font=("Georgia", 20, "bold"), fg=ACCENT_GOTH, bg=BG_COLOR).pack(side="left", expand=True) + + acc_box = tk.Frame(top_bar, bg=PANEL_BG, padx=14, pady=6, highlightthickness=1, highlightbackground=BORDER_COLOR) + acc_box.pack(side="right") + + tk.Label( + acc_box, + text=t("main_acc_header", profile["name"], profile["level"], profile["total_points"]), + font=("Helvetica", 11, "bold"), fg=ACCENT_GOLD, bg=PANEL_BG + ).pack(anchor="e") + + xp_row = tk.Frame(acc_box, bg=PANEL_BG) + xp_row.pack(fill="x", pady=(3, 0)) + ttk.Progressbar( + xp_row, style="Goth.Horizontal.TProgressbar", + orient="horizontal", length=150, mode="determinate", + maximum=profile["needed_xp"], value=profile["current_xp"] + ).pack(side="left", padx=(0, 8)) + tk.Label( + xp_row, text=t("xp_next_level", profile["current_xp"], profile["needed_xp"], profile["level"] + 1), + font=("Helvetica", 8), fg=MUTED_FG, bg=PANEL_BG + ).pack(side="right") + + # Spiel-Karten + cards_section = tk.Frame(container, bg=BG_COLOR) + cards_section.pack(fill="both", expand=True, pady=6) + tk.Label(cards_section, text=t("choose_cardgame"), font=("Helvetica", 12, "bold"), fg=FG_COLOR, bg=BG_COLOR).pack(pady=(0, 6)) + + cards_grid = tk.Frame(cards_section, bg=BG_COLOR) + cards_grid.pack(expand=True) + + if not available_games: + tk.Label(cards_grid, text=t("no_games_found"), font=("Helvetica", 12), fg=MUTED_FG, bg=BG_COLOR).pack(pady=30) + else: + for idx, game in enumerate(available_games): + card_widget = self._create_game_card(cards_grid, game["title"], lambda g=game: self.ctrl.launch_game(g)) + card_widget.grid(row=idx // 4, column=idx % 4, padx=14, pady=8) + + # Statistik-Übersicht + variants = Database.get_variants_for_filter() + filter_map = {t("filter_all_games"): None} + for v in variants: + filter_map[v["translated_name"]] = v["id"] + + StatsBoardWidget( + container, + title=t("stats_account_title", profile["name"]), + filter_map=filter_map, + fetch_callback=lambda vid: Database.get_stats_overview(profile["id"], vid) + ).pack(fill="x", side="bottom", pady=(8, 0)) + + def _create_game_card(self, parent, game_title: str, on_click) -> tk.Canvas: + card_w, card_h = MENU_CARD_SIZE + cv = tk.Canvas(parent, width=card_w, height=card_h, bg=BG_COLOR, highlightthickness=0, cursor="hand2") + + normal_img = hover_img = None + if self.assets.raw_chat_frame: + base = self.assets.raw_chat_frame.resize((card_w, card_h), Image.Resampling.LANCZOS) + bright = ImageEnhance.Brightness(base).enhance(1.22) + normal_img = ImageTk.PhotoImage(base) + hover_img = ImageTk.PhotoImage(bright) + self._card_refs.extend([normal_img, hover_img]) + bg_id = cv.create_image(0, 0, image=normal_img, anchor="nw") + else: + bg_id = cv.create_rectangle(4, 4, card_w - 4, card_h - 4, fill=PANEL_BG, outline=ACCENT_GOTH, width=2) + + txt_id = cv.create_text( + card_w // 2, card_h // 2, + text=game_title, width=card_w - 36, justify="center", + font=("Georgia", 15, "bold"), fill=FG_COLOR + ) + + cv.bind("", lambda e: (cv.itemconfigure(bg_id, image=hover_img) if hover_img else None, cv.itemconfigure(txt_id, fill=ACCENT_GOLD))) + cv.bind("", lambda e: (cv.itemconfigure(bg_id, image=normal_img) if normal_img else None, cv.itemconfigure(txt_id, fill=FG_COLOR))) + cv.bind("", lambda e: (self.sounds.play("click"), on_click())) + return cv \ No newline at end of file diff --git a/view/menus/__pycache__/login_view.cpython-311.pyc b/view/menus/__pycache__/login_view.cpython-311.pyc new file mode 100644 index 0000000..feb9dbc Binary files /dev/null and b/view/menus/__pycache__/login_view.cpython-311.pyc differ diff --git a/view/menus/__pycache__/main_menu_view.cpython-311.pyc b/view/menus/__pycache__/main_menu_view.cpython-311.pyc new file mode 100644 index 0000000..435b71b Binary files /dev/null and b/view/menus/__pycache__/main_menu_view.cpython-311.pyc differ diff --git a/view/menus/__pycache__/statistics_view.cpython-311.pyc b/view/menus/__pycache__/statistics_view.cpython-311.pyc new file mode 100644 index 0000000..4bcee35 Binary files /dev/null and b/view/menus/__pycache__/statistics_view.cpython-311.pyc differ diff --git a/view/menus/login_view.py b/view/menus/login_view.py new file mode 100644 index 0000000..5b46d4b --- /dev/null +++ b/view/menus/login_view.py @@ -0,0 +1,109 @@ +# -*- coding: utf-8 -*- +import tkinter as tk +from tkinter import ttk +from resources.code_res.game_constants import ( + ACCENT_GOLD, ACCENT_GOTH, BG_COLOR, BORDER_COLOR, FG_COLOR, INPUT_BG, MUTED_FG, SUBTLE_BORDER +) +from resources.code_res.i18n import t +from view.dialogs.audio_settings_dialog import AudioSettingsDialog +from view.widgets.image_button import ImageButton + + +class LoginView: + def __init__(self, root_view): + self.root = root_view + self.ctrl = root_view.ctrl + self.assets = root_view.assets + self.sounds = root_view.ctrl.sounds + self.profile_var = None + self.new_name_var = None + + def show(self, profiles: list[str], preselect_name: str = ""): + self.root.clear_window(apply_global_bg=True) + + # Weiter eingerückt, damit die Spinnennetze in der Ecke frei bleiben + top_controls = tk.Frame(self.root, bg=BG_COLOR) + top_controls.place(relx=0.93, rely=0.07, anchor="ne") + + ImageButton( + top_controls, t("btn_lang"), self.assets.raw_sel, self.assets.raw_sel_active, + lambda: self.ctrl.toggle_language(), sound_mgr=self.sounds, width=115, height=36, font=("Helvetica", 10, "bold") + ).pack(side="left", padx=(0, 8)) + + ImageButton( + top_controls, t("btn_audio"), self.assets.raw_sel, self.assets.raw_sel_active, + lambda: AudioSettingsDialog.open(self.root, self.assets, self.sounds), + sound_mgr=self.sounds, width=105, height=36, font=("Helvetica", 10, "bold") + ).pack(side="left") + + main_frame = tk.Frame( + self.root, bg=BG_COLOR, padx=40, pady=32, + highlightthickness=1, highlightbackground=SUBTLE_BORDER + ) + main_frame.place(relx=0.5, rely=0.5, anchor="center") + + # Titeltext direkt AUF die violette title1.png Plakette setzen + title_photo = self.assets.get_scaled_photo("title_login", self.assets.raw_title, (420, 96)) + if title_photo: + title_lbl = tk.Label( + main_frame, + image=title_photo, + text="GOTH CARD\nCOLLECTION", + compound="center", + font=("Georgia", 18, "bold"), + fg=ACCENT_GOLD, + bg=BG_COLOR, + bd=0, + ) + title_lbl.image = title_photo + title_lbl.pack(pady=(0, 20)) + else: + tk.Label( + main_frame, text=t("app_title").upper(), + font=("Georgia", 22, "bold"), fg=ACCENT_GOTH, bg=BG_COLOR + ).pack(pady=(0, 20)) + + if profiles: + tk.Label( + main_frame, text=t("login_select_lbl"), + font=("Helvetica", 10), fg=MUTED_FG, bg=BG_COLOR + ).pack(anchor="w", padx=10) + + frame = tk.Frame(main_frame, bg=BG_COLOR) + frame.pack(pady=(4, 12)) + initial_prof = preselect_name if preselect_name in profiles else profiles[0] + self.profile_var = tk.StringVar(value=initial_prof) + cb = ttk.Combobox( + frame, textvariable=self.profile_var, values=profiles, + state="readonly", font=("Helvetica", 12), width=19, style="Goth.TCombobox" + ) + cb.grid(row=0, column=0, padx=(0, 12), ipady=3) + ImageButton( + frame, t("login_btn"), self.assets.raw_btn, self.assets.raw_btn_active, + lambda: self.ctrl.do_login(self.profile_var.get()), sound_mgr=self.sounds, width=155, height=40 + ).grid(row=0, column=1) + + tk.Frame(main_frame, bg=SUBTLE_BORDER, height=1).pack(fill="x", padx=10, pady=14) + + tk.Label( + main_frame, text=t("login_create_lbl"), + font=("Helvetica", 10), fg=MUTED_FG, bg=BG_COLOR + ).pack(anchor="w", padx=10) + + new_frame = tk.Frame(main_frame, bg=BG_COLOR) + new_frame.pack(pady=(4, 4)) + self.new_name_var = tk.StringVar() + entry = tk.Entry( + new_frame, textvariable=self.new_name_var, font=("Helvetica", 13), + bg=INPUT_BG, fg=FG_COLOR, bd=0, width=20, + highlightthickness=1, highlightbackground=BORDER_COLOR, insertbackground="white" + ) + entry.grid(row=0, column=0, padx=(0, 12), ipady=6) + entry.bind("", lambda e: self.ctrl.do_create_profile(self.new_name_var.get().strip())) + if not profiles: + entry.focus_set() + + ImageButton( + new_frame, t("new_profile_btn"), self.assets.raw_btn, self.assets.raw_btn_active, + lambda: self.ctrl.do_create_profile(self.new_name_var.get().strip()), sound_mgr=self.sounds, width=155, height=40 + ).grid(row=0, column=1) \ No newline at end of file diff --git a/view/menus/main_menu_view.py b/view/menus/main_menu_view.py new file mode 100644 index 0000000..884ed6b --- /dev/null +++ b/view/menus/main_menu_view.py @@ -0,0 +1,253 @@ +# -*- coding: utf-8 -*- +# view/menus/main_menu_view.py +import tkinter as tk + +from models.database import Database +from resources.code_res.game_constants import ( + ACCENT_GOLD, ACCENT_GOTH, BG_COLOR, BORDER_COLOR, CAT_LUCK, + CAT_ONLINE, ERROR_FG, FG_COLOR, GAME_CATEGORIES, MENU_CARD_SIZE, + MUTED_FG, PANEL_BG, SUBTLE_BORDER +) +from resources.code_res.i18n import t +from view.dialogs.audio_settings_dialog import AudioSettingsDialog +from view.widgets.image_button import ImageButton + + +class MainMenuView: + def __init__(self, root_view): + self.root = root_view + self.ctrl = root_view.ctrl + self.assets = root_view.assets + self.sounds = root_view.ctrl.sounds + self.selected_category: str = CAT_LUCK + + def show( + self, + profile: dict, + available_games: list[dict], + devils_resume_only: bool = False, + category: str | None = None, + ): + self.root.clear_window(apply_global_bg=True) + + valid_cats = {c[0] for c in GAME_CATEGORIES} + if category in valid_cats: + self.selected_category = category + Database.save_setting("last_menu_category", category) + else: + saved_cat = Database.load_setting("last_menu_category", CAT_LUCK) + self.selected_category = saved_cat if saved_cat in valid_cats else CAT_LUCK + + container = tk.Frame( + self.root, bg=BG_COLOR, padx=26, pady=16, + highlightthickness=1, highlightbackground=SUBTLE_BORDER + ) + container.place(relx=0.5, rely=0.52, anchor="center", relwidth=0.90, relheight=0.86) + + # Symmetrische 3-Spalten-Topbar + top_bar = tk.Frame(container, bg=BG_COLOR) + top_bar.pack(fill="x", pady=(0, 12)) + top_bar.columnconfigure(0, weight=1, uniform="hdr") + top_bar.columnconfigure(1, weight=1, uniform="hdr") + top_bar.columnconfigure(2, weight=1, uniform="hdr") + + left_btns = tk.Frame(top_bar, bg=BG_COLOR) + left_btns.grid(row=0, column=0, sticky="w") + + if not devils_resume_only: + ImageButton( + left_btns, t("btn_switch_profile"), self.assets.raw_sel, self.assets.raw_sel_active, + self.ctrl.logout_to_login, sound_mgr=self.sounds, width=145, height=36, font=("Helvetica", 9, "bold") + ).pack(side="left", padx=(0, 5)) + + ImageButton( + left_btns, t("btn_stats"), self.assets.raw_sel, self.assets.raw_sel_active, + self.ctrl.show_statistics, sound_mgr=self.sounds, width=110, height=36, font=("Helvetica", 9, "bold") + ).pack(side="left", padx=(0, 5)) + + ImageButton( + left_btns, t("btn_lang"), self.assets.raw_sel, self.assets.raw_sel_active, + lambda: self.ctrl.toggle_language(), sound_mgr=self.sounds, width=105, height=36, font=("Helvetica", 9, "bold") + ).pack(side="left", padx=(0, 5)) + + ImageButton( + left_btns, t("btn_audio"), self.assets.raw_sel, self.assets.raw_sel_active, + lambda: AudioSettingsDialog.open(self.root, self.assets, self.sounds), + sound_mgr=self.sounds, width=85, height=36, font=("Helvetica", 9, "bold") + ).pack(side="left") + + tk.Label( + top_bar, text=t("header_title"), + font=("Georgia", 18, "bold"), fg=ACCENT_GOTH, bg=BG_COLOR + ).grid(row=0, column=1) + + acc_box = tk.Frame(top_bar, bg=PANEL_BG, padx=16, pady=7, highlightthickness=1, highlightbackground=BORDER_COLOR) + acc_box.grid(row=0, column=2, sticky="e") + tk.Label( + acc_box, + text=t("main_acc_soul_only", profile["name"]), + font=("Georgia", 12, "bold"), fg=ACCENT_GOLD, bg=PANEL_BG + ).pack() + + tk.Frame(container, bg=SUBTLE_BORDER, height=1).pack(fill="x", pady=(0, 12)) + + cards_section = tk.Frame(container, bg=BG_COLOR) + cards_section.pack(fill="both", expand=True) + + # Im aktiven Devil's Deal sind alle Kategorien gesperrt -> nur Resume! + if devils_resume_only: + pakt_panel = tk.Frame( + cards_section, bg=PANEL_BG, padx=36, pady=28, + highlightthickness=2, highlightbackground=ERROR_FG + ) + pakt_panel.place(relx=0.5, rely=0.5, anchor="center") + + tk.Label( + pakt_panel, text=t("devils_deal_resume_title"), + font=("Georgia", 18, "bold"), fg=ERROR_FG, bg=PANEL_BG + ).pack(pady=(0, 8)) + tk.Label( + pakt_panel, text=t("devils_deal_resume_desc"), + font=("Helvetica", 11), fg=MUTED_FG, bg=PANEL_BG, wraplength=520, justify="center" + ).pack(pady=(0, 22)) + + resume_card = self._create_game_card( + pakt_panel, t("devils_deal_resume_card"), "", self.ctrl.resume_devils_deal, bg_col=PANEL_BG + ) + resume_card.pack() + return + + # --- FLACHE 4-KATEGORIEN-LEISTE (keine Unterkategorien!) --- + cat_bar = tk.Frame( + cards_section, bg=PANEL_BG, padx=16, pady=10, + highlightthickness=1, highlightbackground=BORDER_COLOR + ) + cat_bar.pack(fill="x", pady=(0, 14)) + + tabs_wrap = tk.Frame(cat_bar, bg=PANEL_BG) + tabs_wrap.pack() + + active_cat_title = "" + active_cat_desc = "" + for cat_id, title_key, desc_key in GAME_CATEGORIES: + c_title = t(title_key) + is_sel = (cat_id == self.selected_category) + if is_sel: + active_cat_title = c_title + active_cat_desc = t(desc_key) + + pil_norm = self.assets.raw_btn if is_sel else self.assets.raw_sel + pil_hov = self.assets.raw_btn_active if is_sel else self.assets.raw_sel_active + btn_w = 205 if cat_id == "party_offline" else 155 + + ImageButton( + tabs_wrap, c_title, pil_norm, pil_hov, + lambda cid=cat_id: self.show(profile, available_games, devils_resume_only=False, category=cid), + sound_mgr=self.sounds, width=btn_w, height=38, font=("Helvetica", 10, "bold") + ).pack(side="left", padx=6) + + is_online_tab = (self.selected_category == CAT_ONLINE) + tk.Label( + cat_bar, + text=active_cat_desc, + font=("Helvetica", 10, "bold" if is_online_tab else "normal"), + fg=ERROR_FG if is_online_tab else MUTED_FG, + bg=PANEL_BG, + ).pack(pady=(8, 2)) + + # --- GEFILTERTES SPIELKARTEN-GRID --- + filtered_games = [g for g in available_games if g.get("category", CAT_LUCK) == self.selected_category] + + cards_grid = tk.Frame(cards_section, bg=BG_COLOR) + cards_grid.pack(expand=True) + + if not filtered_games: + empty_box = tk.Frame( + cards_grid, bg=PANEL_BG, padx=32, pady=22, + highlightthickness=1, highlightbackground=ERROR_FG if is_online_tab else SUBTLE_BORDER + ) + empty_box.pack(pady=30) + tk.Label( + empty_box, + text=t("no_games_in_category", active_cat_title), + font=("Georgia", 12, "bold"), + fg=ERROR_FG if is_online_tab else MUTED_FG, + bg=PANEL_BG, + ).pack() + else: + for idx, game in enumerate(filtered_games): + prog = game.get("progress") + sub_txt = t("menu_card_rank_sub", prog["title"], prog["level"]) if prog else "" + card_widget = self._create_game_card( + cards_grid, + game["title"], + sub_txt, + lambda g=game: self.ctrl.launch_game(g), + is_online=is_online_tab, + ) + card_widget.grid(row=idx // 4, column=idx % 4, padx=18, pady=12) + + def _create_game_card( + self, parent, game_title: str, rank_subtitle: str, on_click, bg_col: str = BG_COLOR, is_online: bool = False + ) -> tk.Canvas: + card_w, card_h = MENU_CARD_SIZE + cv = tk.Canvas(parent, width=card_w, height=card_h, bg=bg_col, highlightthickness=0, cursor="hand2") + + base_outline = ERROR_FG if is_online else BORDER_COLOR + gem_color = ERROR_FG if is_online else ACCENT_GOTH + + outer_id = cv.create_rectangle( + 4, 4, card_w - 4, card_h - 4, + fill=PANEL_BG, outline=base_outline, width=2 + ) + inner_id = cv.create_rectangle( + 12, 12, card_w - 12, card_h - 12, + fill="#16131c", outline=SUBTLE_BORDER, width=1 + ) + top_gem = cv.create_text(card_w // 2, 28, text="†" if is_online else "❖", font=("Georgia", 11, "bold"), fill=gem_color) + bot_gem = cv.create_text(card_w // 2, card_h - 28, text="†" if is_online else "❖", font=("Georgia", 11, "bold"), fill=gem_color) + + longest_word = max((len(w) for w in game_title.replace("\n", " ").split()), default=0) + title_size = 13 if longest_word >= 11 else 15 + title_y = (card_h // 2 - 22) if rank_subtitle else (card_h // 2) + + txt_id = cv.create_text( + card_w // 2, title_y, + text=game_title, width=card_w - 32, justify="center", + font=("Georgia", title_size, "bold"), fill=FG_COLOR + ) + + sub_id = None + if rank_subtitle: + cv.create_line( + 36, card_h // 2 + 4, card_w - 36, card_h // 2 + 4, + fill=SUBTLE_BORDER, width=1 + ) + sub_id = cv.create_text( + card_w // 2, card_h // 2 + 34, + text=rank_subtitle, width=card_w - 30, justify="center", + font=("Helvetica", 9, "bold"), fill=gem_color + ) + + def _on_enter(_e): + cv.itemconfigure(outer_id, outline=ACCENT_GOLD) + cv.itemconfigure(inner_id, fill="#211c2a", outline=gem_color) + cv.itemconfigure(txt_id, fill=ACCENT_GOLD) + cv.itemconfigure(top_gem, fill=ACCENT_GOLD) + cv.itemconfigure(bot_gem, fill=ACCENT_GOLD) + if sub_id: + cv.itemconfigure(sub_id, fill="#ffffff") + + def _on_leave(_e): + cv.itemconfigure(outer_id, outline=base_outline) + cv.itemconfigure(inner_id, fill="#16131c", outline=SUBTLE_BORDER) + cv.itemconfigure(txt_id, fill=FG_COLOR) + cv.itemconfigure(top_gem, fill=gem_color) + cv.itemconfigure(bot_gem, fill=gem_color) + if sub_id: + cv.itemconfigure(sub_id, fill=gem_color) + + cv.bind("", _on_enter) + cv.bind("", _on_leave) + cv.bind("", lambda e: (self.sounds.play("click"), on_click())) + return cv \ No newline at end of file diff --git a/view/menus/statistics_view.py b/view/menus/statistics_view.py new file mode 100644 index 0000000..699a44f --- /dev/null +++ b/view/menus/statistics_view.py @@ -0,0 +1,120 @@ +# -*- coding: utf-8 -*- +# view/menus/statistics_view.py +import tkinter as tk +from tkinter import ttk +from models.database import Database +from resources.code_res.game_constants import ( + ACCENT_GOLD, ACCENT_GOTH, BG_COLOR, BORDER_COLOR, + FG_COLOR, PANEL_BG, STAT_GAME_GROUPS, SUBTLE_BORDER +) +from resources.code_res.i18n import t +from view.dialogs.audio_settings_dialog import AudioSettingsDialog +from view.widgets.image_button import ImageButton +from view.widgets.stats_board_widget import StatsBoardWidget + + +class StatisticsView: + def __init__(self, root_view): + self.root = root_view + self.ctrl = root_view.ctrl + self.assets = root_view.assets + self.sounds = root_view.ctrl.sounds + self.selected_folder = STAT_GAME_GROUPS[0][0] + + def show(self, profile: dict, folder_path: str | None = None): + if folder_path is not None: + self.selected_folder = folder_path + + self.root.clear_window(apply_global_bg=True) + + topbar = tk.Frame(self.root, bg=PANEL_BG, padx=14, pady=8, highlightthickness=1, highlightbackground=SUBTLE_BORDER) + topbar.pack(fill="x", side="top") + + ImageButton( + topbar, t("btn_back_main"), self.assets.raw_sel, self.assets.raw_sel_active, + self.ctrl.show_main_menu, sound_mgr=self.sounds, width=145, height=36, font=("Helvetica", 10, "bold") + ).pack(side="left") + + tk.Label( + topbar, text=t("stats_view_topbar", profile["name"]), + font=("Georgia", 15, "bold"), fg=FG_COLOR, bg=PANEL_BG + ).pack(side="left", expand=True) + + right_btns = tk.Frame(topbar, bg=PANEL_BG) + right_btns.pack(side="right") + + ImageButton( + right_btns, t("btn_lang"), self.assets.raw_sel, self.assets.raw_sel_active, + lambda: self.ctrl.toggle_language(lambda: self.show(self.ctrl.active_profile, self.selected_folder)), + sound_mgr=self.sounds, width=110, height=34, font=("Helvetica", 9, "bold") + ).pack(side="left", padx=(0, 6)) + + ImageButton( + right_btns, t("btn_audio"), self.assets.raw_sel, self.assets.raw_sel_active, + lambda: AudioSettingsDialog.open(self.root, self.assets, self.sounds), + sound_mgr=self.sounds, width=92, height=34, font=("Helvetica", 9, "bold") + ).pack(side="left") + + container = tk.Frame(self.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, 14)) + + tk.Label( + selector_panel, text=t("stats_select_game_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") + + active_game_title = "" + for folder, title_key in STAT_GAME_GROUPS: + g_title = t(title_key) + is_selected = (folder == self.selected_folder) + if is_selected: + active_game_title = g_title + pil_norm = self.assets.raw_btn if is_selected else self.assets.raw_sel + pil_hov = self.assets.raw_btn_active if is_selected else self.assets.raw_sel_active + + ImageButton( + tabs_row, g_title, pil_norm, pil_hov, + lambda f=folder: self.show(profile, folder_path=f), + sound_mgr=self.sounds, width=165, height=38, font=("Helvetica", 10, "bold") + ).pack(side="left", padx=(0, 8)) + + # Spielgebundene Rang- & XP-Leiste für das gewählte Spiel + g_prog = Database.get_game_progress(profile["id"], self.selected_folder) + rank_bar = tk.Frame(container, bg=PANEL_BG, padx=18, pady=10, highlightthickness=1, highlightbackground=SUBTLE_BORDER) + rank_bar.pack(fill="x", pady=(0, 14)) + + tk.Label( + rank_bar, + text=t("stats_game_rank_info", active_game_title, g_prog["title"], g_prog["level"], g_prog["current_xp"], g_prog["needed_xp"]), + font=("Georgia", 11, "bold"), fg=ACCENT_GOTH, bg=PANEL_BG + ).pack(side="left") + + ttk.Progressbar( + rank_bar, style="Goth.Horizontal.TProgressbar", + orient="horizontal", length=220, mode="determinate", + maximum=g_prog["needed_xp"], value=g_prog["current_xp"] + ).pack(side="right") + + game_variants = Database.get_variants_for_filter(folder_path=self.selected_folder) + filter_map = {t("stats_all_variants_of_game", active_game_title): None} + for v in game_variants: + filter_map[v["translated_name"]] = v["id"] + + board = StatsBoardWidget( + container, + title=t("stats_game_board_title", active_game_title), + filter_map=filter_map, + fetch_callback=lambda vid: Database.get_stats_overview( + profile["id"], variant_id=vid, folder_path=self.selected_folder + ) + ) + board.pack(fill="x") \ No newline at end of file diff --git a/view/widgets/__pycache__/bot_setup_widget.cpython-311.pyc b/view/widgets/__pycache__/bot_setup_widget.cpython-311.pyc new file mode 100644 index 0000000..2164e11 Binary files /dev/null and b/view/widgets/__pycache__/bot_setup_widget.cpython-311.pyc differ diff --git a/view/widgets/__pycache__/image_button.cpython-311.pyc b/view/widgets/__pycache__/image_button.cpython-311.pyc new file mode 100644 index 0000000..3ffa008 Binary files /dev/null and b/view/widgets/__pycache__/image_button.cpython-311.pyc differ diff --git a/view/widgets/__pycache__/resizing_bg.cpython-311.pyc b/view/widgets/__pycache__/resizing_bg.cpython-311.pyc new file mode 100644 index 0000000..f45a1cc Binary files /dev/null and b/view/widgets/__pycache__/resizing_bg.cpython-311.pyc differ diff --git a/view/widgets/__pycache__/stats_board_widget.cpython-311.pyc b/view/widgets/__pycache__/stats_board_widget.cpython-311.pyc new file mode 100644 index 0000000..b08b16f Binary files /dev/null and b/view/widgets/__pycache__/stats_board_widget.cpython-311.pyc differ diff --git a/view/widgets/bot_setup_widget.py b/view/widgets/bot_setup_widget.py new file mode 100644 index 0000000..db098c0 --- /dev/null +++ b/view/widgets/bot_setup_widget.py @@ -0,0 +1,80 @@ +# -*- coding: utf-8 -*- +# view/widgets/bot_setup_widget.py +import tkinter as tk +from tkinter import ttk +from resources.code_res.game_constants import ( + BORDER_COLOR, BOT_LEVEL_COUNT, CELL_BG, FG_COLOR, INPUT_BG, MUTED_FG, SUBTLE_BORDER +) +from resources.code_res.i18n import t + + +class BotSetupWidget(tk.Frame): + """Wiederverwendbares Gegner-Auswahl-Panel mit Aktiv-/Inaktiv-Schaltung.""" + def __init__(self, parent, saved_configs: dict[int, tuple[str, int]], max_bots: int = 3, enabled: bool = True): + super().__init__(parent, bg=CELL_BG, padx=14, pady=10, highlightthickness=1, highlightbackground=SUBTLE_BORDER) + self.rows_data = [] + self._labels = [] + + self.level_labels = [t("none_bot")] + [t(f"bot_level_{i}") for i in range(BOT_LEVEL_COUNT)] + self.label_to_lvl = {self.level_labels[0]: -1} + for i in range(BOT_LEVEL_COUNT): + self.label_to_lvl[t(f"bot_level_{i}")] = i + + for slot in range(max_bots): + default_name = t("bot_default_name", slot + 1) + saved_name, saved_lvl = saved_configs.get(slot, (default_name, -1)) + if not saved_name.strip(): + saved_name = default_name + + row = tk.Frame(self, bg=CELL_BG) + row.pack(fill="x", pady=3) + + lbl = tk.Label( + row, text=t("opponent_label", slot + 1), + font=("Helvetica", 10, "bold"), fg=FG_COLOR, bg=CELL_BG, width=10, anchor="w" + ) + lbl.pack(side="left") + self._labels.append(lbl) + + name_var = tk.StringVar(value=saved_name) + ent = tk.Entry( + row, textvariable=name_var, font=("Helvetica", 10), + bg=INPUT_BG, fg=FG_COLOR, disabledbackground="#16141c", disabledforeground="#666070", + bd=0, width=16, highlightthickness=1, highlightbackground=BORDER_COLOR, insertbackground="white" + ) + ent.pack(side="left", padx=(4, 10), ipady=4) + + init_lbl = self.level_labels[0] + if 0 <= saved_lvl < BOT_LEVEL_COUNT: + init_lbl = t(f"bot_level_{saved_lvl}") + + lvl_var = tk.StringVar(value=init_lbl) + cb = ttk.Combobox( + row, textvariable=lvl_var, values=self.level_labels, + state="readonly", font=("Helvetica", 10), width=32, style="Goth.TCombobox" + ) + cb.pack(side="left", fill="x", expand=True) + + self.rows_data.append((slot, name_var, lvl_var, ent, cb)) + + self.set_enabled(enabled) + + def set_enabled(self, enabled: bool): + for lbl in self._labels: + lbl.configure(fg=FG_COLOR if enabled else MUTED_FG) + for _slot, _nvar, _lvar, ent, cb in self.rows_data: + ent.configure(state="normal" if enabled else "disabled") + cb.configure(state="readonly" if enabled else "disabled") + + def collect_configs(self) -> tuple[list[tuple[int, str]], dict[int, tuple[str, int]]]: + active_bots: list[tuple[int, str]] = [] + to_persist: dict[int, tuple[str, int]] = {} + + for slot, name_var, lvl_var, _ent, _cb in self.rows_data: + clean_name = name_var.get().strip() or t("bot_default_name", slot + 1) + ai_lvl = self.label_to_lvl.get(lvl_var.get(), -1) + to_persist[slot] = (clean_name, ai_lvl) + if ai_lvl >= 0: + active_bots.append((ai_lvl, clean_name)) + + return active_bots, to_persist \ No newline at end of file diff --git a/view/widgets/image_button.py b/view/widgets/image_button.py new file mode 100644 index 0000000..94d59fc --- /dev/null +++ b/view/widgets/image_button.py @@ -0,0 +1,108 @@ +# -*- coding: utf-8 -*- +# view/widgets/image_button.py +import tkinter as tk +from PIL import Image, ImageEnhance, ImageTk +from resources.code_res.game_constants import BG_COLOR, FG_COLOR + + +class ImageButton(tk.Label): + """Rahmenloser Alpha-PNG-Button mit echtem Graufilter für inaktive Zustände (enabled=False).""" + def __init__( + self, + parent, + text: str, + pil_normal, + pil_hover, + command, + sound_mgr=None, + width: int = 180, + height: int = 42, + font=("Helvetica", 11, "bold"), + enabled: bool = True, + ): + try: + parent_bg = parent.cget("bg") + except Exception: + parent_bg = BG_COLOR + + self._normal_photo = None + self._hover_photo = None + self._disabled_photo = None + + if pil_normal: + resized_norm = pil_normal.resize((width, height), Image.Resampling.LANCZOS) + self._normal_photo = ImageTk.PhotoImage(resized_norm) + + # Automatischer Grau- & Abdunklungsfilter für nicht klickbare Buttons + gray_base = ImageEnhance.Color(resized_norm).enhance(0.0) + dimmed = ImageEnhance.Brightness(gray_base).enhance(0.55) + self._disabled_photo = ImageTk.PhotoImage(dimmed) + + if pil_hover: + resized_hov = pil_hover.resize((width, height), Image.Resampling.LANCZOS) + self._hover_photo = ImageTk.PhotoImage(resized_hov) + + self._sound_mgr = sound_mgr + self._user_cmd = command + self._enabled = bool(enabled) + + init_img = self._normal_photo if self._enabled else self._disabled_photo + init_fg = FG_COLOR if self._enabled else "#777282" + + super().__init__( + parent, + text=text, + image=init_img if init_img else "", + compound="center", + font=font, + fg=init_fg, + bg=parent_bg, + bd=0, + padx=0, + pady=0, + highlightthickness=0, + cursor="hand2" if self._enabled else "arrow", + ) + + self.bind("", self._on_enter) + self.bind("", self._on_leave) + self.bind("", self._on_click) + + def set_enabled(self, enabled: bool): + self._enabled = bool(enabled) + if self._enabled: + self.configure( + image=self._normal_photo if self._normal_photo else "", + fg=FG_COLOR, + cursor="hand2", + ) + else: + self.configure( + image=self._disabled_photo if self._disabled_photo else "", + fg="#777282", + cursor="arrow", + ) + + def _on_enter(self, _event): + if not self._enabled: + return + if self._hover_photo: + self.configure(image=self._hover_photo, fg="#ffffff") + else: + self.configure(fg="#ffffff") + + def _on_leave(self, _event): + if not self._enabled: + return + if self._normal_photo: + self.configure(image=self._normal_photo, fg=FG_COLOR) + else: + self.configure(fg=FG_COLOR) + + def _on_click(self, _event): + if not self._enabled: + return + if self._sound_mgr: + self._sound_mgr.play("click") + if self._user_cmd: + self._user_cmd() \ No newline at end of file diff --git a/view/widgets/resizing_bg.py b/view/widgets/resizing_bg.py new file mode 100644 index 0000000..34451d7 --- /dev/null +++ b/view/widgets/resizing_bg.py @@ -0,0 +1,23 @@ +# -*- coding: utf-8 -*- +import tkinter as tk +from PIL import Image, ImageTk + + +class ResizingBG(tk.Label): + def __init__(self, parent, pil_image, **kwargs): + super().__init__(parent, bd=0, **kwargs) + self.raw_img = pil_image + self._photo = None + self._resize_job = None + self.bind("", self._on_resize) + + def _on_resize(self, event): + if self._resize_job: + self.after_cancel(self._resize_job) + w, h = max(1, event.width), max(1, event.height) + self._resize_job = self.after(60, lambda: self._render(w, h)) + + def _render(self, w, h): + resized = self.raw_img.resize((w, h), Image.Resampling.LANCZOS) + self._photo = ImageTk.PhotoImage(resized) + self.configure(image=self._photo) \ No newline at end of file diff --git a/view/widgets/stats_board_widget.py b/view/widgets/stats_board_widget.py new file mode 100644 index 0000000..f800d87 --- /dev/null +++ b/view/widgets/stats_board_widget.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +import tkinter as tk +from tkinter import ttk +from resources.code_res.game_constants import ( + ACCENT_GOTH, BORDER_COLOR, CELL_BG, FG_COLOR, + MUTED_FG, PANEL_BG, STAT_FIELD_KEYS, SUBTLE_BORDER +) +from resources.code_res.i18n import t + + +class StatsBoardWidget(tk.Frame): + def __init__(self, parent, title: str, filter_map: dict[str, int | None], fetch_callback): + super().__init__( + parent, bg=PANEL_BG, padx=16, pady=12, + highlightthickness=1, highlightbackground=BORDER_COLOR + ) + self.filter_map = filter_map + self.fetch_callback = fetch_callback + + header = tk.Frame(self, bg=PANEL_BG) + header.pack(fill="x", pady=(0, 8)) + + self.title_lbl = tk.Label(header, text=title, font=("Georgia", 12, "bold"), fg=ACCENT_GOTH, bg=PANEL_BG) + self.title_lbl.pack(side="left") + + first_key = next(iter(filter_map.keys())) + self.filter_var = tk.StringVar(value=first_key) + self.filter_cb = ttk.Combobox( + header, textvariable=self.filter_var, + values=list(filter_map.keys()), state="readonly", + width=28, style="Goth.TCombobox" + ) + self.filter_cb.pack(side="right") + + grid = tk.Frame(self, bg=PANEL_BG) + grid.pack(fill="x") + for col in range(4): + grid.columnconfigure(col, weight=1) + + self.value_labels = {} + for i, (stat_key, i18n_key) in enumerate(STAT_FIELD_KEYS): + r, c = divmod(i, 4) + cell = tk.Frame(grid, bg=CELL_BG, padx=10, pady=6, highlightthickness=1, highlightbackground=SUBTLE_BORDER) + cell.grid(row=r, column=c, padx=4, pady=3, sticky="nsew") + tk.Label(cell, text=t(i18n_key), font=("Helvetica", 9), fg=MUTED_FG, bg=CELL_BG).pack(anchor="w") + val_lbl = tk.Label(cell, text="0", font=("Helvetica", 12, "bold"), fg=FG_COLOR, bg=CELL_BG) + val_lbl.pack(anchor="w", pady=(1, 0)) + self.value_labels[stat_key] = val_lbl + + self.filter_cb.bind("<>", lambda e: self.refresh()) + self.refresh() + + def set_title(self, new_title: str): + self.title_lbl.configure(text=new_title) + + def refresh(self): + vid = self.filter_map.get(self.filter_var.get()) + data = self.fetch_callback(vid) + for k, lbl in self.value_labels.items(): + lbl.configure(text=str(data.get(k, "0"))) \ No newline at end of file