first commit

This commit is contained in:
thw 2026-11-14 05:25:51 +01:00
commit 163a3665d2
149 changed files with 6706 additions and 0 deletions

179
README.md Normal file
View File

@ -0,0 +1,179 @@
# † The Goth Cardgame Collection †
**[Deutsch](#deutsch) | [English](#english)**
---
<a name="deutsch"></a>
## 🇩🇪 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)
---
<a name="english"></a>
## 🇬🇧 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)

Binary file not shown.

Binary file not shown.

Binary file not shown.

129
controller/app_context.py Normal file
View File

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

View File

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

49
controller/game_loader.py Normal file
View File

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

0
games/__init__.py Normal file
View File

Binary file not shown.

214
games/blackjack/README.md Normal file
View File

@ -0,0 +1,214 @@
# † Blackjack – Devil's Gambit †
**[Deutsch](#deutsch) | [English](#english)**
---
<a name="deutsch"></a>
## 🇩🇪 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
```
---
<a name="english"></a>
## 🇬🇧 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
```

Binary file not shown.

View File

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

View File

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

View File

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

View File

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

View File

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

42
games/blackjack/start.py Normal file
View File

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

View File

@ -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("<Return>", lambda _e: create_new_account())
ImageButton(
create_grid, t("bj_create_acc_btn", BJ_STARTING_GOLD),
self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active,
create_new_account, sound_mgr=self.ctx.sounds,
width=185, height=34, font=("Helvetica", 9, "bold"),
enabled=can_create_more,
).grid(row=0, column=2, sticky="e", pady=4)
# --- Info / Divine Punishment / The Devil's Deal ---
min_sac_lvl = Progression.get_devils_deal_min_level()
if devils_deal_open and has_accounts:
tk.Label(
acc_box,
text=t("bj_devils_deal_warn", min_sac_lvl, DEVILS_DEAL_GOLD_REWARD),
font=("Helvetica", 8, "bold"), fg=ERROR_FG, bg=CELL_BG, wraplength=480, justify="left"
).pack(anchor="w", pady=(6, 4))
sac_candidates = Database.get_sacrificeable_profiles(pid, GAME_FOLDER_ID)
if sac_candidates:
devil_row = tk.Frame(acc_box, bg=CELL_BG)
devil_row.pack(fill="x", pady=(2, 0))
sac_map = {f"{c['name']} ({c['title']} • Lv. {c['level']})": c["id"] for c in sac_candidates}
sac_var = tk.StringVar(value=next(iter(sac_map.keys())))
ttk.Combobox(
devil_row, textvariable=sac_var, values=list(sac_map.keys()),
state="readonly", font=("Helvetica", 9), width=26, style="Goth.TCombobox"
).pack(side="left", fill="x", expand=True, padx=(0, 8))
def seal_devils_deal():
cur = get_current_acc()
victim_id = sac_map.get(sac_var.get())
if cur is None or victim_id is None:
return
active_bots, to_save = self.bot_widget.collect_configs() if self.bot_widget else ([], {})
Database.save_bot_configs(pid, GAME_FOLDER_ID, to_save)
ok, _msg = Database.execute_devils_deal(pid, GAME_FOLDER_ID, victim_id, cur["id"])
if ok:
self.ctx.sounds.play("end_battle")
BlackjackTableView(
self.ctx,
variant_key="bj_classic",
bj_account_id=cur["id"],
bot_configs=active_bots,
on_back_to_menu=lambda acc_id, msg="": self.show(preselect_id=acc_id, status_msg=msg),
)
ImageButton(
devil_row, t("bj_devils_deal_btn", DEVILS_DEAL_GOLD_REWARD),
self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active,
seal_devils_deal, sound_mgr=None, width=185, height=32, font=("Helvetica", 9, "bold")
).pack(side="right")
else:
tk.Label(
acc_box, text=t("bj_devils_deal_none", min_sac_lvl),
font=("Helvetica", 8), fg=MUTED_FG, bg=CELL_BG
).pack(anchor="w")
else:
info_text = (
t("bj_divine_punishment_warn", f"{dyn_xp_cost:,}".replace(",", "."), XP_TO_GOLD_AMOUNT)
if is_divine
else t("bj_acc_limit_info", GOLD_MAX_ACCOUNTS, BJ_INITIAL_ANTE, dyn_xp_cost, XP_TO_GOLD_AMOUNT)
)
tk.Label(
acc_box, text=info_text,
font=("Helvetica", 8, "bold" if is_divine else "normal"),
fg=ERROR_FG if is_divine else MUTED_FG,
bg=CELL_BG, wraplength=480, justify="left"
).pack(anchor="w", pady=(6, 0))
# =====================================================================
# SPALTE 2: Gegner-Setup (inaktiv ausgegraut, solange kein Konto existiert)
# =====================================================================
right_col = tk.Frame(upper_split, bg=PANEL_BG)
right_col.grid(row=0, column=1, sticky="nsew", padx=(10, 0))
tk.Label(
right_col, text=t("bj_bots_sec_title"),
font=("Georgia", 12, "bold"), fg=ACCENT_GOTH if has_accounts else MUTED_FG, bg=PANEL_BG
).pack(anchor="w", pady=(0, 6))
saved_bots = Database.load_bot_configs(pid, GAME_FOLDER_ID)
self.bot_widget = BotSetupWidget(right_col, saved_bots, max_bots=BJ_MAX_BOTS, enabled=has_accounts)
self.bot_widget.pack(fill="both", expand=True)
fb_lbl = tk.Label(
main_card, textvariable=feedback_var,
font=("Helvetica", 9, "bold"),
fg="#7be08a" if status_is_ok else ERROR_FG,
bg=PANEL_BG
)
fb_lbl.pack(anchor="w", pady=(2, 4))
# =====================================================================
# SEKTION 3: Spielvariante wählen (Buttons mit Graufilter, wenn Konto fehlt / < 10 Gold)
# =====================================================================
tk.Label(
main_card, text=t("bj_sec3_title"),
font=("Georgia", 12, "bold"), fg=ACCENT_GOTH if has_accounts else MUTED_FG, bg=PANEL_BG
).pack(anchor="w", pady=(2, 8))
def enter_table(v_key: str):
fb_lbl.configure(fg=ERROR_FG)
cur = get_current_acc()
if not cur:
return
acc = Database.get_blackjack_account(cur["id"])
if not acc:
return
Database.save_setting(setting_key, str(acc["id"]))
active_bots, configs_to_save = self.bot_widget.collect_configs()
Database.save_bot_configs(pid, GAME_FOLDER_ID, configs_to_save)
cur_bj_prog = self.ctx.refresh_game_progress()
if acc["gold"] < GOLD_MIN_TABLE_ENTRY:
feedback_var.set(t(
"bj_err_not_enough_gold_entry",
acc["account_name"], GOLD_MIN_TABLE_ENTRY, acc["gold"],
cur_bj_prog["xp_exchange_cost"], XP_TO_GOLD_AMOUNT
))
return
BlackjackTableView(
self.ctx, v_key, acc["id"], active_bots,
on_back_to_menu=lambda acc_id, msg="": self.show(preselect_id=acc_id, status_msg=msg)
)
variants_row = tk.Frame(main_card, bg=PANEL_BG)
variants_row.pack(fill="x")
for idx in range(len(BJ_VARIANTS)):
variants_row.columnconfigure(idx, weight=1)
table_buttons: list[ImageButton] = []
can_enter_now = bool(active_acc and active_acc["gold"] >= GOLD_MIN_TABLE_ENTRY)
for idx, (v_key, cfg) in enumerate(BJ_VARIANTS.items()):
card = tk.Frame(variants_row, bg=CELL_BG, padx=16, pady=12, highlightthickness=1, highlightbackground=SUBTLE_BORDER)
card.grid(row=0, column=idx, padx=(0, 8) if idx == 0 else (8, 0), sticky="nsew")
tk.Label(
card, text=t(f"variant_{v_key}"),
font=("Georgia", 12, "bold"), fg=FG_COLOR if has_accounts else MUTED_FG, bg=CELL_BG
).pack(anchor="w")
tk.Label(
card, text=t("bj_variant_desc", cfg["decks"], BJ_INITIAL_ANTE),
font=("Helvetica", 9), fg=MUTED_FG, bg=CELL_BG
).pack(anchor="w", pady=(4, 10))
t_btn = ImageButton(
card, t("bj_enter_table_btn"),
self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active,
lambda k=v_key: enter_table(k),
sound_mgr=self.ctx.sounds, width=160, height=36,
font=("Helvetica", 10, "bold"), enabled=can_enter_now,
)
t_btn.pack(anchor="e")
table_buttons.append(t_btn)
# Live-Aktualisierung beim Konto-Wechsel im Dropdown
def on_account_switched(*_):
cur = get_current_acc()
if cur is not None:
fresh = Database.get_blackjack_account(cur["id"])
Database.save_setting(setting_key, str(fresh["id"]))
gold_var.set(t("bj_gold_display_lbl", fresh["gold"]))
topbar.extra_label.configure(text=t("bj_header_gold", fresh["account_name"], fresh["gold"]))
playable = fresh["gold"] >= GOLD_MIN_TABLE_ENTRY
for tb in table_buttons:
tb.set_enabled(playable)
feedback_var.set("")
acc_cb.bind("<<ComboboxSelected>>", on_account_switched)

View File

@ -0,0 +1,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")

File diff suppressed because it is too large Load Diff

View File

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

17
main.py Normal file
View File

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

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

37
models/card.py Normal file
View File

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

430
models/database.py Normal file
View File

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

35
models/deck.py Normal file
View File

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

184
models/progression.py Normal file
View File

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

View File

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

103
models/sound_manager.py Normal file
View File

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

View File

Binary file not shown.

View File

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

View File

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

View File

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

Binary file not shown.

View File

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

View File

@ -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 = ?;
""",
},
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 410 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

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