diff --git a/build_scripts/build.bat b/build_scripts/build.bat index 36e148e..a0850ef 100644 --- a/build_scripts/build.bat +++ b/build_scripts/build.bat @@ -174,15 +174,22 @@ if "%DO_WIN%"=="1" ( set "ICON_ARG=--icon %PROJECT_ROOT%\resources\images\game_icon.ico" ) + set "VER_ARG=" + if exist "%PROJECT_ROOT%\build_scripts\version_info.txt" ( + set "VER_ARG=--version-file %PROJECT_ROOT%\build_scripts\version_info.txt" + ) + !WIN_PY! -m PyInstaller ^ --noconfirm ^ --noconsole ^ --onefile ^ + --noupx ^ --clean ^ --distpath "%PROJECT_ROOT%\dist\windows" ^ --workpath "%PROJECT_ROOT%\build\windows" ^ --specpath "%PROJECT_ROOT%\build\windows" ^ !ICON_ARG! ^ + !VER_ARG! ^ --add-data "%PROJECT_ROOT%\resources;resources" ^ --add-data "%PROJECT_ROOT%\games;games" ^ --collect-submodules games ^ @@ -451,7 +458,7 @@ scp -P %OSX_SSH_PORT% "!TMP_TAR!" %OSX_SSH_USER%@%OSX_SSH_HOST%:%OSX_REMOTE_DIR% del /q "!TMP_TAR!" 2>nul echo [OSX-VM] Kompiliere native macOS-Binary + .app Bundle in der VM... -ssh -p %OSX_SSH_PORT% %OSX_SSH_USER%@%OSX_SSH_HOST% "export PATH=/Library/Frameworks/Python.framework/Versions/3.11/bin:/opt/homebrew/bin:/usr/local/bin:$PATH; cd %OSX_REMOTE_DIR% && tar -xzf src.tar.gz && rm -f src.tar.gz && tr -d '\r' < build_scripts/build.sh > build_scripts/_osx.sh && mv build_scripts/_osx.sh build_scripts/build.sh && chmod +x build_scripts/build.sh && ./build_scripts/build.sh --OSX && tar -czf dist/macos/%APP_NAME%_macOS.tar.gz -C dist/macos ." +ssh -p %OSX_SSH_PORT% %OSX_SSH_USER%@%OSX_SSH_HOST% "export PATH=/Library/Frameworks/Python.framework/Versions/3.11/bin:/opt/homebrew/bin:/usr/local/bin:$PATH; cd %OSX_REMOTE_DIR% && tar -xzf src.tar.gz && rm -f src.tar.gz && ( [ -x .venv_build_macos/bin/python3 ] || (rm -rf .venv_build_macos && python3 -m venv .venv_build_macos) ) && ( .venv_build_macos/bin/python3 -c 'import PIL, pygame, PyInstaller' >/dev/null 2>&1 || .venv_build_macos/bin/python3 -m pip install --upgrade pip pillow pygame pyinstaller ) && ICON_OPT=''; if [ -f resources/images/game_icon.icns ]; then ICON_OPT='--icon resources/images/game_icon.icns'; elif [ -f resources/images/game_icon.ico ]; then ICON_OPT='--icon resources/images/game_icon.ico'; fi && .venv_build_macos/bin/python3 -m PyInstaller --noconfirm --windowed --onefile --noupx --clean --osx-bundle-identifier de.kuro.thegothcardgamecollection --distpath dist/macos --workpath build/macos --specpath build/macos $ICON_OPT --add-data 'resources:resources' --add-data 'games:games' --collect-submodules games --collect-submodules controller --collect-submodules models --collect-submodules view --collect-submodules resources --hidden-import tkinter --hidden-import tkinter.ttk --hidden-import tkinter.font --hidden-import sqlite3 --hidden-import PIL._tkinter_finder --name %APP_NAME% main.py && chmod +x dist/macos/%APP_NAME% 2>/dev/null || true && rm -rf build/macos && tar -czf dist/macos/%APP_NAME%_macOS.tar.gz -C dist/macos ." if errorlevel 1 ( echo [ERROR] macOS-Build in der VM fehlgeschlagen! if "!VM_WAS_RUNNING!"=="0" "!VBOX_MANAGE!" controlvm "%OSX_VM_NAME%" acpipowerbutton >nul 2>nul @@ -474,4 +481,4 @@ if "!VM_WAS_RUNNING!"=="0" ( "!VBOX_MANAGE!" controlvm "%OSX_VM_NAME%" acpipowerbutton >nul 2>nul ) echo [OK] macOS-Build fertig unter: dist\macos\ -exit /b 0 +exit /b 0 \ No newline at end of file diff --git a/build_scripts/build.sh b/build_scripts/build.sh index 995b993..9fa142d 100644 --- a/build_scripts/build.sh +++ b/build_scripts/build.sh @@ -1,8 +1,8 @@ #!/usr/bin/env bash # -*- coding: utf-8 -*- -# Lokales Build-Skript (Linux / WSL / macOS-Zielsystem) +# Lokales Build-Skript (nur Linux & Windows via Wine) # Ablageort: build_scripts/build.sh -# Targets: --Win | --Unix | --OSX | --current | --all | --clean +# Targets: --Win | --Unix | --current | --all | --clean set -e SCRIPT_PATH="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/$(basename "${BASH_SOURCE[0]}")" @@ -11,17 +11,16 @@ cd "${PROJECT_ROOT}" APP_NAME="TheGothCardgameCollection" ICON_ICO="${PROJECT_ROOT}/resources/images/game_icon.ico" +VERSION_TXT="${PROJECT_ROOT}/build_scripts/version_info.txt" UNAME_OUT="$(uname -s)" case "${UNAME_OUT}" in - Linux*) HOST_OS="linux" ;; - Darwin*) HOST_OS="macos" ;; - *) echo "❌ Unbekanntes System: ${UNAME_OUT}"; exit 1 ;; + Linux*) ;; + *) echo "❌ Dieses Skript unterstützt nur Linux-Systeme (gefunden: ${UNAME_OUT})."; exit 1 ;; esac DO_WIN=0 DO_UNIX=0 -DO_OSX=0 DO_CLEAN=0 ORIG_ARGS=("$@") @@ -31,16 +30,11 @@ for arg in "$@"; do --clean) DO_CLEAN=1 ;; --win|--windows) DO_WIN=1 ;; --unix|--linux) DO_UNIX=1 ;; - --osx|--macos) DO_OSX=1 ;; - --current) - if [ "$HOST_OS" = "macos" ]; then DO_OSX=1; else DO_UNIX=1; fi - ;; - --all) - if [ "$HOST_OS" = "macos" ]; then - DO_OSX=1 - else - DO_WIN=1; DO_UNIX=1 - fi + --current) DO_UNIX=1 ;; + --all) DO_WIN=1; DO_UNIX=1 ;; + *) + echo "❌ Unbekannte Option: $arg (Erlaubt: --Win | --Unix | --current | --all | --clean)" + exit 1 ;; esac done @@ -51,25 +45,24 @@ if [ "$DO_CLEAN" -eq 1 ]; then exit 0 fi -if [ "$DO_WIN" -eq 0 ] && [ "$DO_UNIX" -eq 0 ] && [ "$DO_OSX" -eq 0 ]; then - if [ "$HOST_OS" = "macos" ]; then DO_OSX=1; else DO_UNIX=1; fi +# Standardziel ohne Parameter: nativer Linux-Build +if [ "$DO_WIN" -eq 0 ] && [ "$DO_UNIX" -eq 0 ]; then + DO_UNIX=1 fi # Root/Sudo Check unter Linux falls Systempakete fehlen NEEDS_SYS_INSTALL=0 -if [ "$HOST_OS" = "linux" ]; then - if [ "$DO_UNIX" -eq 1 ]; then - if ! command -v python3 &>/dev/null || ! python3 -c "import tkinter" &>/dev/null || ! python3 -m pip --version &>/dev/null; then - NEEDS_SYS_INSTALL=1 - fi - fi - if [ "$DO_WIN" -eq 1 ] && ! command -v wine &>/dev/null; then +if [ "$DO_UNIX" -eq 1 ]; then + if ! command -v python3 &>/dev/null || ! python3 -c "import tkinter" &>/dev/null || ! python3 -m pip --version &>/dev/null; then NEEDS_SYS_INSTALL=1 fi - if [ "$NEEDS_SYS_INSTALL" -eq 1 ] && [ "${EUID:-$(id -u)}" -ne 0 ]; then - echo "🔒 Fehlende Systempakete erkannt – fordere sudo an..." - exec sudo -E bash "$SCRIPT_PATH" "${ORIG_ARGS[@]}" - fi +fi +if [ "$DO_WIN" -eq 1 ] && ! command -v wine &>/dev/null; then + NEEDS_SYS_INSTALL=1 +fi +if [ "$NEEDS_SYS_INSTALL" -eq 1 ] && [ "${EUID:-$(id -u)}" -ne 0 ]; then + echo "🔒 Fehlende Systempakete erkannt – fordere sudo an..." + exec sudo -E bash "$SCRIPT_PATH" "${ORIG_ARGS[@]}" fi if [ "${EUID:-$(id -u)}" -eq 0 ] && [ -n "${SUDO_USER:-}" ]; then @@ -113,8 +106,8 @@ rebuild_internal_db_if_present() { DB_REBUILT=0 -# 1. LINUX BUILD -if [ "$DO_UNIX" -eq 1 ] && [ "$HOST_OS" = "linux" ]; then +# 1. NATIVER LINUX BUILD (--Unix) +if [ "$DO_UNIX" -eq 1 ]; then echo "---> [UNIX] Baue Linux Executable..." if [ "$NEEDS_SYS_INSTALL" -eq 1 ]; then if command -v apt-get &>/dev/null; then @@ -151,7 +144,7 @@ if [ "$DO_UNIX" -eq 1 ] && [ "$HOST_OS" = "linux" ]; then [ -f "$ICON_ICO" ] && ICON_ARG=(--icon "$ICON_ICO") "${USER_RUNNER[@]}" "$LINUX_PY" -m PyInstaller \ - --noconfirm --noconsole --onefile --clean \ + --noconfirm --noconsole --onefile --noupx --clean \ --distpath "${PROJECT_ROOT}/dist/linux" \ --workpath "${PROJECT_ROOT}/build/linux" \ --specpath "${PROJECT_ROOT}/build/linux" \ @@ -169,12 +162,12 @@ if [ "$DO_UNIX" -eq 1 ] && [ "$HOST_OS" = "linux" ]; then echo "✔ Linux-Build fertig: dist/linux/${APP_NAME}" fi -# 2. WINDOWS BUILD VIA WINE (nur auf Linux) -if [ "$DO_WIN" -eq 1 ] && [ "$HOST_OS" = "linux" ]; then +# 2. WINDOWS BUILD VIA WINE (--Win) +if [ "$DO_WIN" -eq 1 ]; then echo "---> [WIN] Baue Windows .exe (via Wine)..." if ! command -v wine &>/dev/null; then command -v apt-get &>/dev/null && dpkg --add-architecture amd64 2>/dev/null || true - install_linux_pkgs wine wget + install_linux_pkgs wine wget curl fi if [ "$DB_REBUILT" -eq 0 ] && command -v python3 &>/dev/null; then @@ -205,16 +198,24 @@ if [ "$DO_WIN" -eq 1 ] && [ "$HOST_OS" = "linux" ]; then DB_REBUILT=1 fi - "${USER_RUNNER[@]}" wine "$WINE_PY" -m pip install --upgrade pip pillow pygame pyinstaller + if ! "${USER_RUNNER[@]}" wine "$WINE_PY" -c "import PIL, pygame, PyInstaller" &>/dev/null; then + echo "---> [WIN] Installiere fehlende Python-Pakete in Wine..." + "${USER_RUNNER[@]}" wine "$WINE_PY" -m pip install --upgrade pip pillow pygame pyinstaller + fi + WINE_ICON_ARG=() [ -f "$ICON_ICO" ] && WINE_ICON_ARG=(--icon "${WIN_ROOT}\\resources\\images\\game_icon.ico") + WINE_VER_ARG=() + [ -f "$VERSION_TXT" ] && WINE_VER_ARG=(--version-file "${WIN_ROOT}\\build_scripts\\version_info.txt") + "${USER_RUNNER[@]}" wine "$WINE_PY" -m PyInstaller \ - --noconfirm --noconsole --onefile --clean \ + --noconfirm --noconsole --onefile --noupx --clean \ --distpath "${WIN_ROOT}\\dist\\windows" \ --workpath "${WIN_ROOT}\\build\\windows" \ --specpath "${WIN_ROOT}\\build\\windows" \ "${WINE_ICON_ARG[@]}" \ + "${WINE_VER_ARG[@]}" \ --add-data "${WIN_ROOT}\\resources;resources" \ --add-data "${WIN_ROOT}\\games;games" \ --collect-submodules games --collect-submodules controller \ @@ -227,49 +228,6 @@ if [ "$DO_WIN" -eq 1 ] && [ "$HOST_OS" = "linux" ]; then echo "✔ Windows-Build fertig: dist/windows/${APP_NAME}.exe" fi -# 3. NATIVER MACOS BUILD (wird direkt in der macOS-VM ausgeführt) -if [ "$DO_OSX" -eq 1 ] && [ "$HOST_OS" = "macos" ]; then - echo "---> [OSX] Baue native macOS Binary + .app Bundle..." - export PATH="/Library/Frameworks/Python.framework/Versions/3.11/bin:/usr/local/bin:/opt/homebrew/bin:$PATH" - - OSX_VENV="${PROJECT_ROOT}/.venv_build_macos" - if [ -d "$OSX_VENV" ] && [ ! -x "$OSX_VENV/bin/python3" ]; then rm -rf "$OSX_VENV"; fi - [ ! -d "$OSX_VENV" ] && python3 -m venv "$OSX_VENV" - - if [ "$DB_REBUILT" -eq 0 ]; then - rebuild_internal_db_if_present "$OSX_VENV/bin/python3" - DB_REBUILT=1 - fi - - "$OSX_VENV/bin/python3" -m pip install --upgrade pip pillow pygame pyinstaller - - OSX_ICON_ARG=() - if [ -f "${PROJECT_ROOT}/resources/images/game_icon.icns" ]; then - OSX_ICON_ARG=(--icon "${PROJECT_ROOT}/resources/images/game_icon.icns") - elif [ -f "$ICON_ICO" ]; then - OSX_ICON_ARG=(--icon "$ICON_ICO") - fi - - "$OSX_VENV/bin/python3" -m PyInstaller \ - --noconfirm --windowed --onefile --clean \ - --osx-bundle-identifier "de.kuro.thegothcardgamecollection" \ - --distpath "${PROJECT_ROOT}/dist/macos" \ - --workpath "${PROJECT_ROOT}/build/macos" \ - --specpath "${PROJECT_ROOT}/build/macos" \ - "${OSX_ICON_ARG[@]}" \ - --add-data "${PROJECT_ROOT}/resources:resources" \ - --add-data "${PROJECT_ROOT}/games:games" \ - --collect-submodules games --collect-submodules controller \ - --collect-submodules models --collect-submodules view --collect-submodules resources \ - --hidden-import tkinter --hidden-import tkinter.ttk --hidden-import tkinter.font \ - --hidden-import sqlite3 --hidden-import PIL._tkinter_finder \ - --name "${APP_NAME}" "${PROJECT_ROOT}/main.py" - - chmod +x "${PROJECT_ROOT}/dist/macos/${APP_NAME}" 2>/dev/null || true - rm -rf "${PROJECT_ROOT}/build/macos" - echo "✔ macOS-Build fertig: dist/macos/${APP_NAME} (.app)" -fi - if [ "${EUID:-$(id -u)}" -eq 0 ] && [ -n "${SUDO_USER:-}" ]; then chown -R "$SUDO_USER:$SUDO_USER" "${PROJECT_ROOT}/dist" 2>/dev/null || true -fi +fi \ No newline at end of file diff --git a/build_scripts/check_i18n.ps1 b/build_scripts/check_i18n.ps1 new file mode 100644 index 0000000..35e47f0 --- /dev/null +++ b/build_scripts/check_i18n.ps1 @@ -0,0 +1,862 @@ +#Requires -Version 5.1 +<# +.SYNOPSIS + Tiefen-Pruefung aller t(key, *args) i18n-Aufrufe im gesamten Projekt + inklusive verschachtelter Konstanten, Variablenketten, Modul-Importen, + Tupel/Dict-Unpacking, Funktionsparametern und f-Strings. +#> +param( + [switch]$RebuildDb, + [switch]$ShowDynamic +) + +$ErrorActionPreference = "Stop" +[Console]::OutputEncoding = [System.Text.Encoding]::UTF8 + +$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Definition +$ProjectRoot = (Resolve-Path (Join-Path $ScriptDir "..")).Path + +function Find-PythonExe { + $venvPy = Join-Path $ProjectRoot ".venv\Scripts\python.exe" + if (Test-Path $venvPy) { return $venvPy } + + foreach ($cmd in @("python", "python3")) { + $found = Get-Command $cmd -ErrorAction SilentlyContinue + if ($found) { return $found.Source } + } + foreach ($candidate in @( + "C:\Python311\python.exe", + "C:\Python312\python.exe", + "$env:LocalAppData\Programs\Python\Python311\python.exe", + "$env:ProgramFiles\Python311\python.exe" + )) { + if (Test-Path $candidate) { return $candidate } + } + throw "Keine Python-Installation gefunden!" +} + +$PyExe = Find-PythonExe + +if ($RebuildDb) { + $rebuildScript = Join-Path $ProjectRoot "build_scripts\rebuild_internal_db.py" + if (-not (Test-Path $rebuildScript)) { + $rebuildScript = Join-Path $ProjectRoot "rebuild_internal_db.py" + } + if (Test-Path $rebuildScript) { + Write-Host "---> Aktualisiere vorab internal_base.db..." -ForegroundColor Cyan + & $PyExe $rebuildScript + } +} + +$AnalyzerPy = @' +# -*- coding: utf-8 -*- +import ast +import os +import re +import sqlite3 +import sys +from pathlib import Path + +ROOT = Path(sys.argv[1]).resolve() +SHOW_DYNAMIC = "--show-dynamic" in sys.argv[2:] + +EXCLUDE_DIRS = {".git", ".venv", ".venv_build_win", ".venv_build_macos", "build", "dist", "__pycache__"} +SQL_DIR = ROOT / "resources" / "code_res" / "sql" +DB_PATH = ROOT / "resources" / "code_res" / "internal_base.db" + + +# --------------------------------------------------------------------------- +# 1. SQL & SQLite-DB Uebersetzungen einlesen +# --------------------------------------------------------------------------- +def load_sql_translations(sql_dir: Path): + sql_map = {} # key -> {"DE": val, "EN": val} + variants = set() + if not sql_dir.is_dir(): + return sql_map, variants + + tuple_re = re.compile( + r"\(\s*'((?:''|[^'])*)'\s*,\s*'(DE|EN)'\s*,\s*'((?:''|[^'])*)'\s*\)" + ) + var_re = re.compile( + r"\(\s*\d+\s*,\s*'[^']*'\s*,\s*'[^']*'\s*,\s*'([^']+)'\s*," + ) + for sql_file in sorted(sql_dir.glob("*.sql")): + content = sql_file.read_text(encoding="utf-8", errors="replace") + for m in tuple_re.finditer(content): + k = m.group(1).replace("''", "'") + lang = m.group(2) + val = m.group(3).replace("''", "'") + sql_map.setdefault(k, {})[lang] = val + for vm in var_re.finditer(content): + variants.add(vm.group(1)) + return sql_map, variants + + +def load_db_translations(db_path: Path): + db_map = {} + if not db_path.is_file(): + return db_map + conn = sqlite3.connect(f"{db_path.as_uri()}?mode=ro", uri=True) + try: + for k, lang, val in conn.execute("SELECT key, lang, val FROM base_i18n"): + db_map.setdefault(k, {})[lang] = val + finally: + conn.close() + return db_map + + +# --------------------------------------------------------------------------- +# 2. Abstrakte Werte fuer tiefenverschachtelte Konstanten- & Datenfluss-Analyse +# --------------------------------------------------------------------------- +class Val: + """Repräsentiert mögliche String-Werte, Tupel/Listen, Dicts oder f-String-Muster.""" + __slots__ = ("strings", "patterns", "items", "mapping") + + def __init__(self, strings=None, patterns=None, items=None, mapping=None): + self.strings = set(strings) if strings else set() + self.patterns = set(patterns) if patterns else set() + self.items = list(items) if items else [] # list[Val] fuer Tuple/List + self.mapping = dict(mapping) if mapping else {} # dict[str, Val] fuer Dict + + def copy(self): + return Val( + set(self.strings), + set(self.patterns), + [v.copy() for v in self.items], + {k: v.copy() for k, v in self.mapping.items()}, + ) + + def merge(self, other: "Val") -> bool: + if other is None: + return False + changed = False + before_s = len(self.strings) + self.strings |= other.strings + if len(self.strings) != before_s: + changed = True + + before_p = len(self.patterns) + self.patterns |= other.patterns + if len(self.patterns) != before_p: + changed = True + + if len(other.items) > len(self.items): + for i in range(len(self.items), len(other.items)): + self.items.append(other.items[i].copy()) + changed = True + for i in range(min(len(self.items), len(other.items))): + if self.items[i].merge(other.items[i]): + changed = True + + for k, ov in other.mapping.items(): + if k not in self.mapping: + self.mapping[k] = ov.copy() + changed = True + elif self.mapping[k].merge(ov): + changed = True + return changed + + def all_leaf_strings(self) -> set: + out = set(self.strings) + for it in self.items: + out |= it.all_leaf_strings() + for mv in self.mapping.values(): + out |= mv.all_leaf_strings() + return out + + @property + def is_empty(self) -> bool: + return not (self.strings or self.patterns or self.items or self.mapping) + + +# --------------------------------------------------------------------------- +# 3. Projektweite Python-Dateien parsen & Modulnamen bestimmen +# --------------------------------------------------------------------------- +def collect_py_files(root: Path): + modules = {} # mod_name -> (Path, ast.Module) + for dirpath, dirnames, filenames in os.walk(root): + dirnames[:] = [d for d in dirnames if d not in EXCLUDE_DIRS] + for fn in sorted(filenames): + if not fn.endswith(".py"): + continue + fpath = Path(dirpath) / fn + rel = fpath.relative_to(root) + parts = list(rel.with_suffix("").parts) + if parts[-1] == "__init__": + parts = parts[:-1] + mod_name = ".".join(parts) if parts else "__root__" + try: + src = fpath.read_text(encoding="utf-8", errors="replace") + tree = ast.parse(src, filename=str(fpath)) + modules[mod_name] = (fpath, tree) + except SyntaxError as exc: + print(f"[SYNTAX-WARNUNG] {rel}: {exc}") + return modules + + +class ProjectAnalyzer: + def __init__(self, modules: dict): + self.modules = modules + # Globale Modul-Umgebungen: mod_name -> {var_name: Val} + self.mod_envs = {m: {} for m in modules} + # Klassen-Attribute & Instanz-Felder (self.xyz): (mod_name, cls_name) -> {attr: Val} + self.cls_attrs = {} + # Funktions-/Methoden-Parameter aus Aufrufen: func_key -> {param_name: Val} + self.func_param_envs = {} + # Funktions-Definitionen nach Schluessel fuer Call-Propagation + self.func_defs = {} # (mod_name, cls_name_or_None, func_name) -> ast.FunctionDef + # Import-Aliase fuer i18n.t pro Modul: mod_name -> (set_of_direct_t_names, set_of_i18n_mod_aliases) + self.t_aliases = {m: (set(), set()) for m in modules} + # Modul-Aliase (import foo.bar as fb): mod_name -> {alias: target_mod} + self.mod_imports = {m: {} for m in modules} + # From-Importe (from foo import BAR as B): mod_name -> {local_name: (target_mod, orig_name)} + self.sym_imports = {m: {} for m in modules} + + self._index_definitions_and_imports() + + def _resolve_import_target(self, cur_mod: str, module_str: str | None, level: int) -> str: + if level == 0: + return module_str or "" + cur_parts = cur_mod.split(".")[:-1] + up = max(0, level - 1) + base = cur_parts[: max(0, len(cur_parts) - up)] + if module_str: + base.extend(module_str.split(".")) + return ".".join(base) + + def _index_definitions_and_imports(self): + for mod_name, (_fpath, tree) in self.modules.items(): + t_direct, t_mods = self.t_aliases[mod_name] + if mod_name.endswith(".i18n") or mod_name == "i18n": + t_direct.add("t") + + for node in tree.body: + if isinstance(node, ast.Import): + for alias in node.names: + asname = alias.asname or alias.name.split(".")[0] + if alias.name in self.modules: + self.mod_imports[mod_name][asname] = alias.name + if alias.name.endswith(".i18n") or alias.name == "i18n": + t_mods.add(asname) + + elif isinstance(node, ast.ImportFrom): + target_mod = self._resolve_import_target(mod_name, node.module, node.level) + is_i18n = target_mod.endswith(".i18n") or target_mod == "i18n" + for alias in node.names: + local = alias.asname or alias.name + if is_i18n and alias.name == "t": + t_direct.add(local) + full_submod = f"{target_mod}.{alias.name}" if target_mod else alias.name + if full_submod in self.modules: + self.mod_imports[mod_name][local] = full_submod + else: + self.sym_imports[mod_name][local] = (target_mod, alias.name) + + elif isinstance(node, ast.FunctionDef): + self.func_defs[(mod_name, None, node.name)] = node + + elif isinstance(node, ast.ClassDef): + self.cls_attrs.setdefault((mod_name, node.name), {}) + for item in node.body: + if isinstance(item, ast.FunctionDef): + self.func_defs[(mod_name, node.name, item.name)] = item + + def eval_expr(self, node, mod_name: str, local_env: dict, cur_cls: str | None = None) -> Val: + if node is None: + return Val() + + # String- oder Zahlen-Literal + if isinstance(node, ast.Constant): + if isinstance(node.value, (str, int, float)) and not isinstance(node.value, bool): + return Val(strings={str(node.value)}) + return Val() + + # Variablen-Name (Lokal -> Klasse -> Modul -> Import) + if isinstance(node, ast.Name): + nm = node.id + if nm in local_env: + return local_env[nm].copy() + if cur_cls and nm in self.cls_attrs.get((mod_name, cur_cls), {}): + return self.cls_attrs[(mod_name, cur_cls)][nm].copy() + if nm in self.mod_envs.get(mod_name, {}): + return self.mod_envs[mod_name][nm].copy() + if nm in self.sym_imports.get(mod_name, {}): + t_mod, orig = self.sym_imports[mod_name][nm] + if t_mod in self.mod_envs and orig in self.mod_envs[t_mod]: + return self.mod_envs[t_mod][orig].copy() + return Val() + + # Attribut-Zugriff: self.xyz oder modul.KONSTANTE oder Klasse.KONSTANTE + if isinstance(node, ast.Attribute): + if isinstance(node.value, ast.Name): + base = node.value.id + if base == "self" and cur_cls: + return self.cls_attrs.get((mod_name, cur_cls), {}).get(node.attr, Val()).copy() + if base in self.mod_imports.get(mod_name, {}): + t_mod = self.mod_imports[mod_name][base] + return self.mod_envs.get(t_mod, {}).get(node.attr, Val()).copy() + if (mod_name, base) in self.cls_attrs: + return self.cls_attrs[(mod_name, base)].get(node.attr, Val()).copy() + if base in self.sym_imports.get(mod_name, {}): + t_mod, orig_cls = self.sym_imports[mod_name][base] + if (t_mod, orig_cls) in self.cls_attrs: + return self.cls_attrs[(t_mod, orig_cls)].get(node.attr, Val()).copy() + return Val() + + # Tupel / Liste / Set + if isinstance(node, (ast.Tuple, ast.List, ast.Set)): + elems = [self.eval_expr(e, mod_name, local_env, cur_cls) for e in node.elts] + v = Val(items=elems) + for el in elems: + v.strings |= el.strings + v.patterns |= el.patterns + return v + + # Dict-Literal + if isinstance(node, ast.Dict): + mp = {} + all_s = set() + for k_node, v_node in zip(node.keys, node.values): + vv = self.eval_expr(v_node, mod_name, local_env, cur_cls) + all_s |= vv.strings + if k_node is not None: + kv = self.eval_expr(k_node, mod_name, local_env, cur_cls) + for ks in kv.strings: + mp.setdefault(ks, Val()).merge(vv) + return Val(strings=all_s, mapping=mp) + + # Subscript: d[key] oder tup[0] + if isinstance(node, ast.Subscript): + container = self.eval_expr(node.value, mod_name, local_env, cur_cls) + idx_val = self.eval_expr(node.slice, mod_name, local_env, cur_cls) + out = Val() + if container.mapping: + if idx_val.strings: + for ks in idx_val.strings: + if ks in container.mapping: + out.merge(container.mapping[ks]) + else: + for mv in container.mapping.values(): + out.merge(mv) + if container.items: + matched_idx = False + for ks in idx_val.strings: + if ks.lstrip("-").isdigit(): + i = int(ks) + if -len(container.items) <= i < len(container.items): + out.merge(container.items[i]) + matched_idx = True + if not matched_idx and not container.mapping: + for it in container.items: + out.merge(it) + return out + + # Ternary: a if cond else b + if isinstance(node, ast.IfExp): + res = self.eval_expr(node.body, mod_name, local_env, cur_cls) + res.merge(self.eval_expr(node.orelse, mod_name, local_env, cur_cls)) + return res + + # BoolOp: a or b + if isinstance(node, ast.BoolOp): + res = Val() + for v_node in node.values: + res.merge(self.eval_expr(v_node, mod_name, local_env, cur_cls)) + return res + + # String-Verkettung: "variant_" + key + if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add): + lv = self.eval_expr(node.left, mod_name, local_env, cur_cls) + rv = self.eval_expr(node.right, mod_name, local_env, cur_cls) + return self._combine_parts([lv, rv]) + + # f-String: f"variant_{self.variant_key}" + if isinstance(node, ast.JoinedStr): + parts = [] + for p in node.values: + if isinstance(p, ast.Constant) and isinstance(p.value, str): + parts.append(Val(strings={p.value})) + elif isinstance(p, ast.FormattedValue): + sub = self.eval_expr(p.value, mod_name, local_env, cur_cls) + if sub.strings: + parts.append(Val(strings=sub.strings)) + else: + parts.append(Val(patterns={".*"})) + return self._combine_parts(parts) + + # Aufrufe wie dict(STAT_GAME_GROUPS) oder my_dict.get(key, default) + if isinstance(node, ast.Call): + if isinstance(node.func, ast.Name) and node.func.id == "dict" and node.args: + arg0 = self.eval_expr(node.args[0], mod_name, local_env, cur_cls) + mp = {} + for pair in arg0.items: + if len(pair.items) >= 2: + for ks in pair.items[0].strings: + mp.setdefault(ks, Val()).merge(pair.items[1]) + return Val(mapping=mp) + + if isinstance(node.func, ast.Attribute) and node.func.attr == "get": + recv = self.eval_expr(node.func.value, mod_name, local_env, cur_cls) + out = Val() + if recv.mapping: + if node.args: + kv = self.eval_expr(node.args[0], mod_name, local_env, cur_cls) + if kv.strings: + for ks in kv.strings: + if ks in recv.mapping: + out.merge(recv.mapping[ks]) + else: + for mv in recv.mapping.values(): + out.merge(mv) + if len(node.args) >= 2: + out.merge(self.eval_expr(node.args[1], mod_name, local_env, cur_cls)) + return out + + return Val() + + @staticmethod + def _combine_parts(parts: list) -> Val: + """Kartesisches Produkt fuer f-Strings / '+'-Verkettung; faellt bei Unbekannten auf Regex-Muster zurueck.""" + has_wildcard = any(bool(p.patterns) and not p.strings for p in parts) + if not has_wildcard: + acc = {""} + for p in parts: + if not p.strings: + return Val() + nxt = set() + for prefix in acc: + for s in p.strings: + if len(nxt) < 128: + nxt.add(prefix + s) + acc = nxt + return Val(strings=acc) + + regex_pieces = [] + for p in parts: + if p.strings and not p.patterns: + escaped = [re.escape(s) for s in sorted(p.strings)] + regex_pieces.append(f"(?:{'|'.join(escaped)})" if len(escaped) > 1 else escaped[0]) + else: + regex_pieces.append(".+") + return Val(patterns={f"^{''.join(regex_pieces)}$"}) + + def _bind_target(self, target, val: Val, mod_name: str, env: dict, cur_cls: str | None, is_mod_scope: bool) -> bool: + changed = False + if isinstance(target, ast.Name): + dest = self.mod_envs[mod_name] if is_mod_scope else env + if target.id not in dest: + dest[target.id] = val.copy() + return not val.is_empty + return dest[target.id].merge(val) + + if isinstance(target, ast.Attribute) and cur_cls: + if isinstance(target.value, ast.Name) and target.value.id == "self": + cdict = self.cls_attrs.setdefault((mod_name, cur_cls), {}) + if target.attr not in cdict: + cdict[target.attr] = val.copy() + return not val.is_empty + return cdict[target.attr].merge(val) + + if isinstance(target, (ast.Tuple, ast.List)): + for idx, sub_t in enumerate(target.elts): + sub_val = val.items[idx] if idx < len(val.items) else Val() + if self._bind_target(sub_t, sub_val, mod_name, env, cur_cls, is_mod_scope): + changed = True + return changed + + def _propagate_call_args(self, call_node: ast.Call, mod_name: str, local_env: dict, cur_cls: str | None) -> bool: + """Leitet Argument-Werte von Aufrufstellen an Funktions- und Konstruktor-Parameter weiter.""" + target_key = None + is_method_or_init = False + + if isinstance(call_node.func, ast.Name): + fn = call_node.func.id + if (mod_name, None, fn) in self.func_defs: + target_key = (mod_name, None, fn) + elif (mod_name, fn, "__init__") in self.func_defs: + target_key = (mod_name, fn, "__init__") + is_method_or_init = True + elif fn in self.sym_imports.get(mod_name, {}): + t_mod, orig = self.sym_imports[mod_name][fn] + if (t_mod, None, orig) in self.func_defs: + target_key = (t_mod, None, orig) + elif (t_mod, orig, "__init__") in self.func_defs: + target_key = (t_mod, orig, "__init__") + is_method_or_init = True + + elif isinstance(call_node.func, ast.Attribute): + if isinstance(call_node.func.value, ast.Name) and call_node.func.value.id == "self" and cur_cls: + mname = call_node.func.attr + if (mod_name, cur_cls, mname) in self.func_defs: + target_key = (mod_name, cur_cls, mname) + is_method_or_init = True + + if target_key is None: + return False + + fdef = self.func_defs[target_key] + param_names = [a.arg for a in fdef.args.args] + if is_method_or_init and param_names and param_names[0] in ("self", "cls"): + param_names = param_names[1:] + + penv = self.func_param_envs.setdefault(target_key, {}) + changed = False + + for i, arg_node in enumerate(call_node.args): + if i < len(param_names): + av = self.eval_expr(arg_node, mod_name, local_env, cur_cls) + if not av.is_empty: + pname = param_names[i] + if pname not in penv: + penv[pname] = av.copy() + changed = True + elif penv[pname].merge(av): + changed = True + + for kw in call_node.keywords: + if kw.arg and kw.arg in param_names: + kv = self.eval_expr(kw.value, mod_name, local_env, cur_cls) + if not kv.is_empty: + if kw.arg not in penv: + penv[kw.arg] = kv.copy() + changed = True + elif penv[kw.arg].merge(kv): + changed = True + return changed + + def _walk_statements(self, stmts, mod_name: str, env: dict, cur_cls: str | None, is_mod_scope: bool, collect_calls: list | None): + changed = False + for stmt in stmts: + if isinstance(stmt, ast.Assign): + val = self.eval_expr(stmt.value, mod_name, env, cur_cls) + for tgt in stmt.targets: + if self._bind_target(tgt, val, mod_name, env, cur_cls, is_mod_scope): + changed = True + elif isinstance(stmt, ast.AnnAssign) and stmt.value is not None: + val = self.eval_expr(stmt.value, mod_name, env, cur_cls) + if self._bind_target(stmt.target, val, mod_name, env, cur_cls, is_mod_scope): + changed = True + elif isinstance(stmt, ast.For): + iter_val = self._eval_iter_items(stmt.iter, mod_name, env, cur_cls) + for elem_val in iter_val: + if self._bind_target(stmt.target, elem_val, mod_name, env, cur_cls, False): + changed = True + if self._walk_statements(stmt.body, mod_name, env, cur_cls, False, collect_calls): + changed = True + if self._walk_statements(stmt.orelse, mod_name, env, cur_cls, False, collect_calls): + changed = True + elif isinstance(stmt, (ast.If, ast.While)): + if self._walk_statements(stmt.body, mod_name, env, cur_cls, is_mod_scope, collect_calls): + changed = True + if self._walk_statements(stmt.orelse, mod_name, env, cur_cls, is_mod_scope, collect_calls): + changed = True + elif isinstance(stmt, ast.With): + if self._walk_statements(stmt.body, mod_name, env, cur_cls, is_mod_scope, collect_calls): + changed = True + elif isinstance(stmt, ast.Try): + if self._walk_statements(stmt.body, mod_name, env, cur_cls, is_mod_scope, collect_calls): + changed = True + for h in stmt.handlers: + if self._walk_statements(h.body, mod_name, env, cur_cls, is_mod_scope, collect_calls): + changed = True + if self._walk_statements(stmt.orelse, mod_name, env, cur_cls, is_mod_scope, collect_calls): + changed = True + if self._walk_statements(stmt.finalbody, mod_name, env, cur_cls, is_mod_scope, collect_calls): + changed = True + elif isinstance(stmt, ast.ClassDef): + cls_env = {} + for c_stmt in stmt.body: + if isinstance(c_stmt, ast.Assign): + val = self.eval_expr(c_stmt.value, mod_name, cls_env, stmt.name) + for tgt in c_stmt.targets: + if isinstance(tgt, ast.Name): + cdict = self.cls_attrs.setdefault((mod_name, stmt.name), {}) + if tgt.id not in cdict: + cdict[tgt.id] = val.copy() + changed = changed or (not val.is_empty) + elif cdict[tgt.id].merge(val): + changed = True + elif isinstance(c_stmt, ast.FunctionDef): + if self._analyze_function(c_stmt, mod_name, env, stmt.name, collect_calls): + changed = True + elif isinstance(stmt, ast.FunctionDef): + if self._analyze_function(stmt, mod_name, env, cur_cls, collect_calls): + changed = True + + # Ausdruecke innerhalb des aktuellen Statements (ohne verschachtelte defs/classes) scannen + if not isinstance(stmt, (ast.FunctionDef, ast.ClassDef, ast.For, ast.If, ast.While, ast.With, ast.Try)): + if self._scan_expr_tree(stmt, mod_name, env, cur_cls, collect_calls): + changed = True + elif isinstance(stmt, (ast.If, ast.While)): + if self._scan_expr_tree(stmt.test, mod_name, env, cur_cls, collect_calls): + changed = True + return changed + + def _eval_iter_items(self, iter_node, mod_name: str, env: dict, cur_cls: str | None) -> list: + """Extrahiert Element-Werte aus Schleifen wie `for i, (a, b) in enumerate(STAT_FIELD_KEYS):`.""" + if isinstance(iter_node, ast.Call) and isinstance(iter_node.func, ast.Name): + fn = iter_node.func.id + if fn == "enumerate" and iter_node.args: + sub_items = self._eval_iter_items(iter_node.args[0], mod_name, env, cur_cls) + return [Val(items=[Val(strings={str(i)}), it]) for i, it in enumerate(sub_items)] + if fn in ("reversed", "sorted", "list", "tuple") and iter_node.args: + return self._eval_iter_items(iter_node.args[0], mod_name, env, cur_cls) + if fn == "range": + nums = [self.eval_expr(a, mod_name, env, cur_cls) for a in iter_node.args] + if len(nums) == 1 and len(nums[0].strings) == 1 and list(nums[0].strings)[0].isdigit(): + n = min(32, int(list(nums[0].strings)[0])) + return [Val(strings={str(i)}) for i in range(n)] + + v = self.eval_expr(iter_node, mod_name, env, cur_cls) + if v.items: + return v.items + if v.strings: + return [Val(strings={s}) for s in v.strings] + return [] + + def _analyze_function(self, fnode: ast.FunctionDef, mod_name: str, outer_env: dict, cur_cls: str | None, collect_calls: list | None) -> bool: + f_env = {k: v.copy() for k, v in outer_env.items()} + fkey = (mod_name, cur_cls, fnode.name) + + # Default-Parameterwerte binden + all_args = fnode.args.args + defaults = fnode.args.defaults + if defaults: + offset = len(all_args) - len(defaults) + for idx, d_node in enumerate(defaults): + pname = all_args[offset + idx].arg + f_env[pname] = self.eval_expr(d_node, mod_name, outer_env, cur_cls) + + # Aus Aufrufstellen propagierte Parameterwerte einmischen + for pname, pval in self.func_param_envs.get(fkey, {}).items(): + if pname in f_env: + f_env[pname].merge(pval) + else: + f_env[pname] = pval.copy() + + return self._walk_statements(fnode.body, mod_name, f_env, cur_cls, False, collect_calls) + + def _is_t_call(self, call_node: ast.Call, mod_name: str) -> bool: + t_direct, t_mods = self.t_aliases[mod_name] + if isinstance(call_node.func, ast.Name) and call_node.func.id in t_direct: + return True + if ( + isinstance(call_node.func, ast.Attribute) + and call_node.func.attr == "t" + and isinstance(call_node.func.value, ast.Name) + and call_node.func.value.id in t_mods + ): + return True + return False + + def _scan_expr_tree(self, root_node, mod_name: str, env: dict, cur_cls: str | None, collect_calls: list | None) -> bool: + changed = False + + def visit(n, cur_env): + nonlocal changed + if n is None or isinstance(n, (ast.FunctionDef, ast.ClassDef)): + return + + if isinstance(n, ast.Lambda): + l_env = {k: v.copy() for k, v in cur_env.items()} + l_args = n.args.args + l_defs = n.args.defaults + if l_defs: + off = len(l_args) - len(l_defs) + for i, dn in enumerate(l_defs): + l_env[l_args[off + i].arg] = self.eval_expr(dn, mod_name, cur_env, cur_cls) + visit(n.body, l_env) + return + + if isinstance(n, (ast.ListComp, ast.SetComp, ast.GeneratorExp, ast.DictComp)): + c_env = {k: v.copy() for k, v in cur_env.items()} + for gen in n.generators: + visit(gen.iter, c_env) + for elem_v in self._eval_iter_items(gen.iter, mod_name, c_env, cur_cls): + self._bind_target(gen.target, elem_v, mod_name, c_env, cur_cls, False) + for if_n in gen.ifs: + visit(if_n, c_env) + if isinstance(n, ast.DictComp): + visit(n.key, c_env) + visit(n.value, c_env) + else: + visit(n.elt, c_env) + return + + if isinstance(n, ast.Call): + if collect_calls is None: + if self._propagate_call_args(n, mod_name, cur_env, cur_cls): + changed = True + elif self._is_t_call(n, mod_name) and n.args: + key_node = n.args[0] + resolved = self.eval_expr(key_node, mod_name, cur_env, cur_cls) + has_star = any(isinstance(a, ast.Starred) for a in n.args[1:]) + pos_argc = None if has_star else (len(n.args) - 1) + try: + expr_src = ast.unparse(key_node) + except Exception: + expr_src = "" + collect_calls.append({ + "mod": mod_name, + "file": self.modules[mod_name][0], + "line": getattr(n, "lineno", 0), + "expr": expr_src, + "val": resolved, + "argc": pos_argc, + }) + + for child in ast.iter_child_nodes(n): + visit(child, cur_env) + + visit(root_node, env) + return changed + + def run_analysis(self, max_passes: int = 5): + for _ in range(max_passes): + any_change = False + for mod_name, (_fpath, tree) in self.modules.items(): + if self._walk_statements(tree.body, mod_name, {}, None, True, collect_calls=None): + any_change = True + if not any_change: + break + + calls = [] + for mod_name, (_fpath, tree) in self.modules.items(): + self._walk_statements(tree.body, mod_name, {}, None, True, collect_calls=calls) + return calls + + +# --------------------------------------------------------------------------- +# 4. Auswertung & Bericht +# --------------------------------------------------------------------------- +sql_map, sql_variants = load_sql_translations(SQL_DIR) +db_map = load_db_translations(DB_PATH) +ref_map = sql_map if sql_map else db_map + +modules = collect_py_files(ROOT) +analyzer = ProjectAnalyzer(modules) +t_calls = analyzer.run_analysis() + +missing_keys = [] # (key, rel_file, line, expr, missing_where) +incomplete_langs = [] # (key, missing_lang) +db_drift_keys = [] # Keys in SQL, aber noch nicht in internal_base.db +placeholder_issues = [] # (key, rel_file, line, lang, max_ph, given_argc) +unmatched_patterns = [] # (pattern, rel_file, line, expr) +unresolved_dynamic = [] # (rel_file, line, expr) + +# 1. Alle SQL-Keys auf Vollständigkeit (DE & EN) und DB-Sync prüfen +for k in sorted(sql_map.keys()): + langs = sql_map[k] + if "DE" not in langs: + incomplete_langs.append((k, "DE fehlt in SQL")) + if "EN" not in langs: + incomplete_langs.append((k, "EN fehlt in SQL")) + if db_map and (k not in db_map or "DE" not in db_map[k] or "EN" not in db_map[k]): + db_drift_keys.append(k) + +# Prüfen, ob jede registrierte Spielvariante ein 'variant_' hat +for vk in sorted(sql_variants): + full_vk = f"variant_{vk}" + if full_vk not in ref_map: + missing_keys.append((full_vk, "resources/code_res/sql/*.sql", 0, f"game_variants.{vk}", "FEHLT in base_i18n")) + +ph_re = re.compile(r"\{(\d+)\}") +checked_unique_keys = set() + +for entry in t_calls: + rel_file = entry["file"].relative_to(ROOT).as_posix() + line = entry["line"] + expr = entry["expr"] + val: Val = entry["val"] + argc = entry["argc"] + + if val.strings: + for k in sorted(val.strings): + checked_unique_keys.add(k) + in_sql = k in sql_map + in_db = (k in db_map) if db_map else in_sql + + if not in_sql and not in_db: + missing_keys.append((k, rel_file, line, expr, "FEHLT in SQL & DB")) + elif not in_sql and in_db: + missing_keys.append((k, rel_file, line, expr, "Nur in DB, FEHLT in SQL-Dateien")) + else: + src_entry = sql_map.get(k) or db_map.get(k, {}) + if argc is not None: + for lg in ("DE", "EN"): + txt = src_entry.get(lg, "") + idxs = [int(m.group(1)) for m in ph_re.finditer(txt)] + if idxs and max(idxs) >= argc: + placeholder_issues.append((k, rel_file, line, lg, max(idxs) + 1, argc)) + + elif val.patterns: + for pat in sorted(val.patterns): + rx = re.compile(pat) + matches = [k for k in ref_map if rx.match(k)] + if not matches: + unmatched_patterns.append((pat, rel_file, line, expr)) + else: + checked_unique_keys.update(matches) + else: + unresolved_dynamic.append((rel_file, line, expr)) + +print("=" * 74) +print(" GOTH CARDGAME COLLECTION - i18n TIEFEN-PRUEFUNG (AST + KONSTANTEN)") +print("=" * 74) +print(f" Gepruefte Python-Module : {len(modules)}") +print(f" Gefundene t(...)-Aufrufe: {len(t_calls)} ({len(checked_unique_keys)} eindeutige Keys aufgeloest)") +print(f" Keys in SQL-Dateien : {len(sql_map)} | Keys in internal_base.db: {len(db_map)}") +print("-" * 74) + +has_errors = False + +if missing_keys: + has_errors = True + print(f"\n[FEHLER] {len(missing_keys)} fehlende i18n-Keys im Code gefunden:") + for k, rf, ln, ex, reason in missing_keys: + trace = f" (aus `{ex}`)" if ex not in (f"'{k}'", f'"{k}"') else "" + print(f" - '{k}' -> {rf}:{ln}{trace} [{reason}]") + +if unmatched_patterns: + has_errors = True + print(f"\n[FEHLER] {len(unmatched_patterns)} f-String-Muster ohne jeglichen Treffer in SQL/DB:") + for pat, rf, ln, ex in unmatched_patterns: + print(f" - Muster {pat} aus `{ex}` -> {rf}:{ln}") + +if incomplete_langs: + has_errors = True + print(f"\n[FEHLER] {len(incomplete_langs)} unvollstaendige Sprach-Paare (DE/EN):") + for k, msg in incomplete_langs: + print(f" - '{k}': {msg}") + +if placeholder_issues: + has_errors = True + print(f"\n[WARNUNG] {len(placeholder_issues)} Platzhalter-Abweichungen ({{0}}, {{1}}, ...):") + for k, rf, ln, lg, need_n, got_n in placeholder_issues: + print(f" - '{k}' [{lg}] erwartet {need_n} Argument(e), Aufruf uebergibt {got_n} -> {rf}:{ln}") + +if db_drift_keys: + print(f"\n[HINWEIS] {len(db_drift_keys)} Key(s) stehen in .sql, fehlen aber noch in internal_base.db:") + for k in db_drift_keys[:15]: + print(f" - '{k}'") + if len(db_drift_keys) > 15: + print(f" ... und {len(db_drift_keys) - 15} weitere.") + print(" -> Tipp: `python build_scripts/rebuild_internal_db.py` oder `-RebuildDb` ausfuehren!") + +if SHOW_DYNAMIC and unresolved_dynamic: + print(f"\n[INFO] {len(unresolved_dynamic)} rein dynamische Laufzeit-Aufrufe:") + for rf, ln, ex in unresolved_dynamic: + print(f" - {rf}:{ln} -> t({ex})") + +if not has_errors and not db_drift_keys: + print("\n[OK] Alles sauber! Alle aufgeloesten t(...)-Keys existieren vollstaendig in DE & EN.") +print("=" * 74) + +sys.exit(1 if has_errors else 0) +'@ + +$extraArgs = @($ProjectRoot) +if ($ShowDynamic) { $extraArgs += "--show-dynamic" } + +$AnalyzerPy | & $PyExe - @extraArgs +exit $LASTEXITCODE \ No newline at end of file diff --git a/build_scripts/check_multi_class_files.ps1 b/build_scripts/check_multi_class_files.ps1 new file mode 100644 index 0000000..bb8ae33 --- /dev/null +++ b/build_scripts/check_multi_class_files.ps1 @@ -0,0 +1,116 @@ +#Requires -Version 5.1 +<# +.SYNOPSIS + Prueft alle Python-Dateien im Projekt auf mehr als eine Klassendefinition + und gibt den vollen Dateipfad samt Klassennamen aus. +#> +param( + [string]$TargetDir = "", + [switch]$IncludeNested +) + +$ErrorActionPreference = "Stop" +[Console]::OutputEncoding = [System.Text.Encoding]::UTF8 + +if ([string]::IsNullOrWhiteSpace($TargetDir)) { + $ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Definition + # Falls das Skript in build_scripts/ liegt, automatisch eine Ebene hoeher starten, sonst im aktuellen Ordner + if ((Split-Path -Leaf $ScriptDir) -ieq "build_scripts") { + $RootPath = (Resolve-Path (Join-Path $ScriptDir "..")).Path + } else { + $RootPath = (Resolve-Path $ScriptDir).Path + } +} else { + $RootPath = (Resolve-Path $TargetDir).Path +} + +$ExcludeDirs = @(".git", ".venv", ".venv_build_win", ".venv_build_macos", "build", "dist", "__pycache__") + +# Versuche Python fuer 100% exaktes AST-Parsing zu finden, sonst Fallback auf Regex +$PyExe = $null +$venvPy = Join-Path $RootPath ".venv\Scripts\python.exe" +if (Test-Path $venvPy) { + $PyExe = $venvPy +} else { + foreach ($cmd in @("python", "python3")) { + $found = Get-Command $cmd -ErrorAction SilentlyContinue + if ($found) { $PyExe = $found.Source; break } + } +} + +if ($PyExe) { + $PyScript = @' +# -*- coding: utf-8 -*- +import ast +import os +import sys +from pathlib import Path + +root = Path(sys.argv[1]).resolve() +include_nested = "--nested" in sys.argv[2:] +exclude_dirs = {".git", ".venv", ".venv_build_win", ".venv_build_macos", "build", "dist", "__pycache__"} + +def get_classes(tree: ast.AST, nested: bool) -> list[str]: + if not nested: + return [node.name for node in getattr(tree, "body", []) if isinstance(node, ast.ClassDef)] + found = [] + def walk_node(n, prefix=""): + for child in ast.iter_child_nodes(n): + if isinstance(child, ast.ClassDef): + qual = f"{prefix}.{child.name}" if prefix else child.name + found.append(qual) + walk_node(child, qual) + else: + walk_node(child, prefix) + walk_node(tree) + return found + +for dirpath, dirnames, filenames in os.walk(root): + dirnames[:] = sorted(d for d in dirnames if d not in exclude_dirs) + for fn in sorted(filenames): + if not fn.endswith(".py"): + continue + fpath = Path(dirpath) / fn + try: + src = fpath.read_text(encoding="utf-8", errors="replace") + tree = ast.parse(src, filename=str(fpath)) + classes = get_classes(tree, include_nested) + if len(classes) > 1: + print(str(fpath)) + for cls_name in classes: + print(f"- {cls_name}") + print("") + except SyntaxError: + pass +'@ + $pyArgs = @($RootPath) + if ($IncludeNested) { $pyArgs += "--nested" } + $PyScript | & $PyExe - @pyArgs +} +else { + # Reiner PowerShell-Fallback falls kein Python im PATH ist + $ClassRegex = if ($IncludeNested) { '^\s*class\s+([A-Za-z_][A-Za-z0-9_]*)\b' } else { '^class\s+([A-Za-z_][A-Za-z0-9_]*)\b' } + + Get-ChildItem -Path $RootPath -Recurse -File -Filter "*.py" | Where-Object { + $full = $_.FullName + $skip = $false + foreach ($ex in $ExcludeDirs) { + if ($full -match ([regex]::Escape("\$ex\"))) { $skip = $true; break } + } + -not $skip + } | Sort-Object FullName | ForEach-Object { + $classes = New-Object System.Collections.Generic.List[string] + foreach ($line in [System.IO.File]::ReadLines($_.FullName)) { + if ($line -match $ClassRegex) { + $classes.Add($Matches[1]) + } + } + if ($classes.Count -gt 1) { + Write-Output $_.FullName + foreach ($c in $classes) { + Write-Output "- $c" + } + Write-Output "" + } + } +} \ No newline at end of file diff --git a/rebuild_internal_db.py b/build_scripts/rebuild_internal_db.py similarity index 100% rename from rebuild_internal_db.py rename to build_scripts/rebuild_internal_db.py diff --git a/build_scripts/version_info.txt b/build_scripts/version_info.txt new file mode 100644 index 0000000..3544739 --- /dev/null +++ b/build_scripts/version_info.txt @@ -0,0 +1,30 @@ +VSVersionInfo( + ffi=FixedFileInfo( + filevers=(1, 0, 0, 0), + prodvers=(1, 0, 0, 0), + mask=0x3f, + flags=0x0, + OS=0x40004, + fileType=0x1, + subtype=0x0, + date=(0, 0) + ), + kids=[ + StringFileInfo([ + StringTable( + '040704B0', + [ + StringStruct('CompanyName', 'Kuro'), + StringStruct('FileDescription', 'The Goth Cardgame Collection'), + StringStruct('FileVersion', '1.0.0.0'), + StringStruct('InternalName', 'TheGothCardgameCollection'), + StringStruct('LegalCopyright', 'Copyright (C) 2026 Kuro'), + StringStruct('OriginalFilename', 'TheGothCardgameCollection.exe'), + StringStruct('ProductName', 'The Goth Cardgame Collection'), + StringStruct('ProductVersion', '1.0.0.0') + ] + ) + ]), + VarFileInfo([VarStruct('Translation', [1031, 1200])]) + ] +) \ No newline at end of file diff --git a/controller/__pycache__/app_context.cpython-311.pyc b/controller/__pycache__/app_context.cpython-311.pyc index 1516a30..f3d66e6 100644 Binary files a/controller/__pycache__/app_context.cpython-311.pyc and b/controller/__pycache__/app_context.cpython-311.pyc differ diff --git a/controller/app_context.py b/controller/app_context.py index 914c6a9..8a8ace8 100644 --- a/controller/app_context.py +++ b/controller/app_context.py @@ -2,374 +2,25 @@ # controller/app_context.py from __future__ import annotations -import tkinter as tk -from PIL import Image, ImageTk - from models.database import Database -import resources.code_res.game_constants as gc -from resources.code_res.game_constants import ( - BG_COLOR, - FONT_COLOR_BODY_DEFAULT, - FONT_COLOR_HEADING_SUB, - FONT_COLOR_STATUS_LOSS, - FONT_COLOR_TITLE_MAIN, - FONT_SIZE_BODY, - FONT_SIZE_HEADING, - FONT_SIZE_SMALL_MIN, - STAT_GAME_GROUPS, - SUBTLE_BORDER, -) -from resources.code_res.i18n import t from view.dialogs.audio_settings_dialog import AudioSettingsDialog +from view.unified_stats_view import UnifiedStatsView from view.widgets.goth_dropdown import GothDropdown -from view.widgets.image_button import ImageButton +from view.widgets.goth_topbar import GothTopbar, format_compact_user_badge -BG_SAFE_SIDE_RATIO = getattr(gc, "BG_SAFE_SIDE_RATIO", 0.088) -BG_SAFE_TOP_RATIO = getattr(gc, "BG_SAFE_TOP_RATIO", 0.095) +__all__ = ["AppContext", "GothTopbar", "UnifiedStatsView", "format_compact_user_badge"] -_FOLDER_TITLE_KEY_MAP: dict[str, str] = dict(STAT_GAME_GROUPS) - - -def format_compact_user_badge(profile: dict, progress: dict) -> str: - """Nutzername (max. 8 Zeichen), Gesamt-Level als Nummer und Gesamt-EXP (max. 8 Stellen).""" - raw_name = str(profile.get("name", "") or "").strip() - short_name = raw_name[:8] - - lvl_num = int(progress.get("level", 1) or 1) - - raw_exp = progress.get("total_points", progress.get("current_xp", 0)) - exp_val = min(99_999_999, max(0, int(raw_exp or 0))) - exp_str = str(exp_val)[:8] - - return f"{short_name} Lv. {lvl_num} {exp_str} XP" - - -def resolve_clean_topbar_title(game_folder: str, raw_title: str) -> str: - """Reduziert den Topbar-Titel auf den reinen Spielnamen ohne Modus-Zusätze.""" - title_key = _FOLDER_TITLE_KEY_MAP.get(game_folder) - clean_game_name = t(title_key) if title_key else "" - - raw_str = str(raw_title or "").strip() - if not clean_game_name: - for sep in ("•", "|", "—", " - "): - if sep in raw_str: - raw_str = raw_str.split(sep, 1)[0].strip() - return raw_str - - low = raw_str.lower() - if "statistik" in low or "statistic" in low: - return f"{t('btn_stats')}: {clean_game_name}" - - return clean_game_name - - -def sanitize_extra_right_text(extra_text: str) -> str: - txt = str(extra_text or "").strip() - if not txt: - return "" - if "XP)" in txt or "Lv." in txt: - return "" - return txt.replace("•", "-").replace("→", "-").replace("←", "-") - - -class _CanvasTextLabelProxy: - def __init__( - self, - bar_canvas: "GothTopbar", - slot_name: str, - text: str, - color: str, - size_px: int, - sanitizer=None, - ): - self._bar = bar_canvas - self._slot = slot_name - self._sanitizer = sanitizer - self.text = sanitizer(text) if callable(sanitizer) else str(text or "") - self.color = color - self.size_px = size_px - - def configure(self, **kwargs): - changed = False - if "text" in kwargs: - raw = str(kwargs["text"] or "") - new_txt = self._sanitizer(raw) if callable(self._sanitizer) else raw - if new_txt != self.text: - self.text = new_txt - changed = True - if "fg" in kwargs and kwargs["fg"] != self.color: - self.color = kwargs["fg"] - changed = True - if changed: - self._bar.refresh_text_slots() - - config = configure - - -class _LevelBadgeProxy: - def __init__(self, bar_canvas: "GothTopbar", color: str, size_px: int): - self._bar = bar_canvas - self.color = color - self.size_px = size_px - self.text = "" - self.refresh_from_db() - - def refresh_from_db(self): - prof = self._bar.ctx.profile or {} - prog = self._bar.ctx.refresh_game_progress() if prof else {} - self.text = format_compact_user_badge(prof, prog) - - def configure(self, **kwargs): - if "fg" in kwargs and kwargs["fg"] != self.color: - self.color = kwargs["fg"] - self.refresh_from_db() - self._bar.refresh_text_slots() - - config = configure - - -class GothTopbar(tk.Canvas): - """ - Rahmenlose Spiel-Kopfleiste passgenau im oberen Rahmen von background_horizontal.jpg: - - Links/rechts sitzen die Buttons unter der dünnen Rahmenleiste (~4.4%) und innerhalb der Spinnweben (~9.5%). - - Der Spielname sitzt mittig direkt unter der Spitze des Mittel-Ornaments (~11.2%). - """ - - def __init__( - self, - parent, - ctx: "AppContext", - 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, - ): - root_h = max(680, parent.winfo_toplevel().winfo_height()) - self._bar_h = max(84, int(root_h * 0.135)) - - super().__init__( - parent, - height=self._bar_h, - bg=BG_COLOR, - bd=0, - highlightthickness=0, - ) - self.ctx = ctx - self.assets = ctx.assets - self.sounds = ctx.sounds - self._locked_exit = locked_exit - - self._bg_slice_photo: ImageTk.PhotoImage | None = None - self._text_photos: list[ImageTk.PhotoImage] = [] - self._last_size: tuple[int, int, int] = (0, 0, 0) - - self._left_widgets: list[tuple[ImageButton, int]] = [] - self._right_widgets: list[tuple[ImageButton, int]] = [] - self.stats_btn: ImageButton | None = None - - btn_norm = self.assets.raw_btn_default - btn_purp = self.assets.raw_btn_purple - - if not locked_exit: - b_main = ImageButton( - self, t("btn_back_main"), btn_norm, btn_purp, - ctx.back_to_main_menu, sound_mgr=self.sounds, width=110, height=32, style="amethyst" - ) - self._left_widgets.append((b_main, b_main.pixel_width)) - - if on_game_menu is not None: - b_gmenu = ImageButton( - self, t("btn_back_game_menu"), btn_norm, btn_purp, - on_game_menu, sound_mgr=self.sounds, width=108, height=32, style="amethyst" - ) - self._left_widgets.append((b_gmenu, b_gmenu.pixel_width)) - - if on_stats is not None: - self.stats_btn = ImageButton( - self, t("btn_stats"), btn_norm, btn_purp, - on_stats, sound_mgr=self.sounds, width=96, height=32, - enabled=stats_enabled, style="amethyst" - ) - self._left_widgets.append((self.stats_btn, self.stats_btn.pixel_width)) - - b_lang = ImageButton( - self, t("btn_lang"), btn_norm, btn_purp, - lambda: ctx.toggle_language(on_lang_refresh), - sound_mgr=self.sounds, width=96, height=32, style="amethyst" - ) - b_audio = ImageButton( - self, t("btn_audio"), btn_norm, btn_purp, - ctx.open_audio_settings, sound_mgr=self.sounds, width=76, height=32, style="amethyst" - ) - self._right_widgets.append((b_lang, b_lang.pixel_width)) - self._right_widgets.append((b_audio, b_audio.pixel_width)) - - clean_title = resolve_clean_topbar_title(ctx.game_folder, title) - self.title_label = _CanvasTextLabelProxy( - self, - "title", - clean_title, - FONT_COLOR_TITLE_MAIN, - FONT_SIZE_HEADING - 1, - sanitizer=lambda s: resolve_clean_topbar_title(ctx.game_folder, s), - ) - self.extra_label = _CanvasTextLabelProxy( - self, - "extra", - extra_right_text, - FONT_COLOR_HEADING_SUB, - FONT_SIZE_SMALL_MIN + 1, - sanitizer=sanitize_extra_right_text, - ) - self.level_label = _LevelBadgeProxy( - self, - color=FONT_COLOR_BODY_DEFAULT, - size_px=FONT_SIZE_SMALL_MIN + 1, - ) - - self.bind("", self._on_configure) - rw = parent.winfo_toplevel().winfo_width() - if rw >= 200: - self._last_size = (rw, self._bar_h, root_h) - self._render_bg_slice(rw, self._bar_h) - self._layout_items(rw, self._bar_h) - - @property - def total_height(self) -> int: - return self._bar_h - - def _render_bg_slice(self, w: int, bar_h: int): - root_win = self.winfo_toplevel() - rw = max(w, root_win.winfo_width()) - rh = max(bar_h, root_win.winfo_height()) - - if hasattr(self.assets, "get_bg_patch_photo"): - self._bg_slice_photo = self.assets.get_bg_patch_photo(rw, rh, 0, 0, w, bar_h) - else: - src = ( - self.assets.raw_bg_vertical - if (rh > rw and self.assets.raw_bg_vertical is not None) - else (self.assets.raw_bg_horizontal or self.assets.raw_bg) - ) - if src is None: - return - full_scaled = src.resize((rw, rh), Image.Resampling.BILINEAR) - self._bg_slice_photo = ImageTk.PhotoImage(full_scaled.crop((0, 0, w, bar_h))) - - if self._bg_slice_photo is None: - return - self.delete("topbar_bg") - self.create_image(0, 0, image=self._bg_slice_photo, anchor="nw", tags="topbar_bg") - self.tag_lower("topbar_bg") - - def _on_configure(self, event): - if event.widget is not self: - return - w = max(1, event.width) - if w < 100: - return - root_h = max(600, self.winfo_toplevel().winfo_height()) - target_h = max(84, int(root_h * 0.135)) - if target_h != self._bar_h: - self._bar_h = target_h - self.configure(height=target_h) - - self.lift() - if (w, target_h, root_h) == self._last_size: - return - self._last_size = (w, target_h, root_h) - self._render_bg_slice(w, target_h) - self._layout_items(w, target_h) - - def refresh_text_slots(self): - if not self.winfo_exists(): - return - w = self.winfo_width() - if w >= 100: - self._layout_items(w, self._bar_h) - - def _layout_items(self, w: int, bar_h: int | None = None): - if bar_h is None: - bar_h = self._bar_h - self.delete("topbar_fg") - self.delete("topbar_txt") - self._text_photos.clear() - - root_h = max(600, self.winfo_toplevel().winfo_height()) - # Seitlich hinter den Spinnweben (~9.5%) und vertikal unter der oberen Rahmenkante (~4.4%) - pad_x = max(96, int(w * 0.095)) - btn_cy = max(46, int(root_h * 0.072)) - # Spieltitel direkt unter der mittleren Dornenspitze (~11.2%) - title_cy = max(btn_cy + 14, bar_h - 14) - - left_x = pad_x - if self._locked_exit: - lock_ph = self.assets.get_goth_text_photo( - t("devils_deal_locked_badge"), - size_px=FONT_SIZE_BODY, - color=FONT_COLOR_STATUS_LOSS, - align="left", - ) - self._text_photos.append(lock_ph) - self.create_image(left_x, btn_cy, image=lock_ph, anchor="w", tags="topbar_txt") - left_x += lock_ph.width() + 10 - else: - for wgt, bw in self._left_widgets: - bh = wgt.pixel_height - wgt.place(x=left_x, y=btn_cy - bh // 2, width=bw, height=bh) - wgt.lift() - left_x += bw + 6 - - right_x = w - pad_x - for wgt, bw in reversed(self._right_widgets): - bh = wgt.pixel_height - wgt.place(x=right_x - bw, y=btn_cy - bh // 2, width=bw, height=bh) - wgt.lift() - right_x -= (bw + 6) - - if self.level_label.text: - lvl_ph = self.assets.get_goth_text_photo( - self.level_label.text, - size_px=self.level_label.size_px, - color=self.level_label.color, - align="right", - ) - self._text_photos.append(lvl_ph) - self.create_image(right_x - 6, btn_cy, image=lvl_ph, anchor="e", tags="topbar_txt") - right_x -= (lvl_ph.width() + 12) - - if self.extra_label.text and (right_x - left_x) > 220: - ext_ph = self.assets.get_goth_text_photo( - self.extra_label.text, - size_px=self.extra_label.size_px, - color=self.extra_label.color, - align="right", - ) - if (right_x - ext_ph.width() - left_x) >= 90: - self._text_photos.append(ext_ph) - self.create_image(right_x - 4, btn_cy, image=ext_ph, anchor="e", tags="topbar_txt") - right_x -= (ext_ph.width() + 10) - - if self.title_label.text: - title_ph = self.assets.get_goth_text_photo( - self.title_label.text, - size_px=self.title_label.size_px, - color=self.title_label.color, - align="center", - ) - self._text_photos.append(title_ph) - self.create_image(w // 2, title_cy, image=title_ph, anchor="center", tags="topbar_txt") class AppContext: + """Schlanker Spiel-Kontext; Topbar und Statistik laufen zentral über eigene Widgets.""" + 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 + setattr(self.root, "_app_controller", controller) @property def profile(self) -> dict: @@ -386,9 +37,25 @@ class AppContext: GothDropdown.close_any_open_popup() self._ctrl.show_main_menu() - def open_audio_settings(self): + def open_settings(self, on_lang_refresh=None): GothDropdown.close_any_open_popup() - AudioSettingsDialog.open(self.root, self.assets, self.sounds) + AudioSettingsDialog.open( + self.root, + self.assets, + self.sounds, + on_toggle_lang=lambda: self.toggle_language(on_lang_refresh), + ) + + def open_audio_settings(self): + self.open_settings(on_lang_refresh=None) + + def open_stats(self, game_endpoint: str | None = None, on_back=None): + """Öffnet die zentrale Statistik-Ansicht für `game_endpoint` (oder das aktive Spiel).""" + endpoint = self.game_folder if game_endpoint is None else game_endpoint + UnifiedStatsView.open(self, game_endpoint=endpoint, on_back=on_back) + + # Alias für etwaige bestehende Aufrufe + open_global_stats = open_stats def toggle_language(self, refresh_callback=None): GothDropdown.close_any_open_popup() @@ -421,24 +88,29 @@ class AppContext: def build_game_topbar( self, parent, - title: str, + 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, + stats_endpoint: str | None = None, + on_stats_back=None, ) -> GothTopbar: + """Erstellt die universelle Topbar und verknüpft automatisch den Statistik-Endpunkt.""" bar = GothTopbar( parent=parent, ctx=self, + stats_endpoint=stats_endpoint if stats_endpoint is not None else self.game_folder, + on_stats_back=on_stats_back, + stats_enabled=stats_enabled, + on_lang_refresh=on_lang_refresh, + locked_exit=locked_exit, title=title, on_game_menu=on_game_menu, on_stats=on_stats, - stats_enabled=stats_enabled, extra_right_text=extra_right_text, - on_lang_refresh=on_lang_refresh, - locked_exit=locked_exit, ) bar.pack(fill="x", side="top") return bar \ No newline at end of file diff --git a/games/blackjack/views/__pycache__/blackjack_table_view.cpython-311.pyc b/games/blackjack/views/__pycache__/blackjack_table_view.cpython-311.pyc index b3e3768..1eab19e 100644 Binary files a/games/blackjack/views/__pycache__/blackjack_table_view.cpython-311.pyc and b/games/blackjack/views/__pycache__/blackjack_table_view.cpython-311.pyc differ diff --git a/games/blackjack/views/blackjack_table_view.py b/games/blackjack/views/blackjack_table_view.py index 5460567..6228d10 100644 --- a/games/blackjack/views/blackjack_table_view.py +++ b/games/blackjack/views/blackjack_table_view.py @@ -14,14 +14,30 @@ from games.blackjack.models.bot_seat import BlackjackBotSeat from games.blackjack.models.hand_evaluator import HandEvaluator from games.blackjack.models.player_hand import PlayerHand from games.blackjack.views.round_result_dialog import BlackjackResultDialog +from games.solitaire.base.solitaire_bottom_bar import SolitaireBottomBar +from games.solitaire.base.solitaire_theme import SolitaireTableBgRenderer from models.database import Database from models.progression import Progression from resources.code_res.game_constants import ( - ACCENT_GOLD, ACCENT_GOTH, BJ_BOT_CARD_SIZE, BJ_BOT_TURN_DELAY_MS, - BJ_DEALER_DELAY_MS, BJ_INITIAL_ANTE, BJ_SPLIT_CARD_SIZE, - BJ_STARTING_GOLD, BJ_VARIANTS, BORDER_COLOR, CELL_BG, ERROR_FG, - FG_COLOR, GOLD_MIN_TABLE_ENTRY, MUTED_FG, PANEL_BG, - PK_TABLE_IMAGE, PLAYING_CARD_SIZE, SUBTLE_BORDER, TABLE_BG, XP_TO_GOLD_AMOUNT + ACCENT_GOLD, + ACCENT_GOTH, + BJ_BOT_CARD_SIZE, + BJ_BOT_TURN_DELAY_MS, + BJ_DEALER_DELAY_MS, + BJ_INITIAL_ANTE, + BJ_SPLIT_CARD_SIZE, + BJ_STARTING_GOLD, + BJ_VARIANTS, + BORDER_COLOR, + ERROR_FG, + FG_COLOR, + FONT_COLOR_TITLE_MAIN, + FONT_SIZE_BODY, + GOLD_MIN_TABLE_ENTRY, + PK_TABLE_IMAGE, + PLAYING_CARD_SIZE, + TABLE_BG, + XP_TO_GOLD_AMOUNT, ) from resources.code_res.i18n import t from view.widgets.image_button import ImageButton @@ -31,13 +47,6 @@ IMAGES_DIR = Path(__file__).resolve().parents[3] / "resources" / "images" BJ_DEALER_CARD_SIZE = (86, 125) -BJ_OVAL_BOT_COORDS = ( - (0.155, 0.76), # Platz 1: Unten links (Spieler 1) - (0.155, 0.25), # Platz 2: Oben links (Spieler 2) - (0.845, 0.25), # Platz 3: Oben rechts (Spieler 3) - (0.845, 0.76), # Platz 4: Unten rechts (Spieler 4) -) - BJ_SEAT_LAYOUT_BY_COUNT = { 1: (2,), 2: (1, 2), @@ -74,12 +83,18 @@ class BlackjackTableView: self.round_start_time: float = time.time() self._last_popup_payload: dict | None = None self._result_dialog: BlackjackResultDialog | None = None - self._photo_refs = [] - self._turn_job = None + self._photo_refs: list = [] + self._turn_job: str | None = None + self._resize_job: str | None = None + self._last_reveal_state: tuple[bool, bool] = (False, False) + + self._bg_renderer = SolitaireTableBgRenderer(self.ctx.assets.res) self._raw_table_pil: Image.Image | None = self._load_raw_table_image() + self._raw_box_bg_pil: Image.Image | None = self._load_raw_box_bg_image() self._scaled_table_photo: ImageTk.PhotoImage | None = None - self._last_bg_size: tuple[int, int] = (0, 0) + self._cached_table_dims: tuple[int, int] = (0, 0) + self._box_bg_cache: dict[tuple[int, int], ImageTk.PhotoImage] = {} self.ctx.sounds.play_ingame_music() @@ -103,43 +118,195 @@ class BlackjackTableView: img_path = IMAGES_DIR / PK_TABLE_IMAGE if img_path.is_file(): try: - return Image.open(img_path).convert("RGB") + return Image.open(img_path).convert("RGBA") except Exception: return None return None - def _create_fanned_cards_canvas( + @staticmethod + def _load_raw_box_bg_image() -> Image.Image | None: + for fname in ("box_background.png", "box_background.jpg"): + p = IMAGES_DIR / fname + if p.is_file(): + try: + return Image.open(p).convert("RGBA") + except Exception: + pass + return None + + def _canvas_alive(self) -> bool: + try: + return hasattr(self, "arena_canvas") and bool(self.arena_canvas.winfo_exists()) + except Exception: + return False + + def _cancel_jobs(self): + for job in (self._turn_job, self._resize_job): + if job is not None: + try: + self.ctx.root.after_cancel(job) + except Exception: + pass + self._turn_job = None + self._resize_job = None + + def _get_box_bg_photo(self, w: int, h: int) -> ImageTk.PhotoImage | None: + if self._raw_box_bg_pil is None or w < 16 or h < 16: + return None + key = (w, h) + cached = self._box_bg_cache.get(key) + if cached is not None: + return cached + if len(self._box_bg_cache) > 24: + self._box_bg_cache.clear() + scaled = self._raw_box_bg_pil.resize((w, h), Image.Resampling.LANCZOS) + ph = ImageTk.PhotoImage(scaled) + self._box_bg_cache[key] = ph + return ph + + def _draw_framed_panel( self, - parent: tk.Widget, + cx: int, + cy: int, + w: int, + h: int, + frame_style: str = "purple", + status_border: str | None = None, + ): + """Zeichnet `box_background.png` mit gotischem Zierrahmen (`box_purple` / `box_gold_double`).""" + x1, y1 = cx - w // 2, cy - h // 2 + x2, y2 = x1 + w, y1 + h + + inset = 5 + inner_w, inner_h = max(16, w - 2 * inset), max(16, h - 2 * inset) + if hasattr(self.ctx.assets, "get_box_bg_photo"): + bg_ph = self.ctx.assets.get_box_bg_photo((inner_w, inner_h)) + else: + bg_ph = self._get_box_bg_photo(inner_w, inner_h) + + if bg_ph is not None: + self._photo_refs.append(bg_ph) + self.arena_canvas.create_image(cx, cy, image=bg_ph, anchor="center", tags="fg") + else: + self.arena_canvas.create_rectangle( + x1 + inset, y1 + inset, x2 - inset, y2 - inset, + fill="#110e18", outline="", tags="fg", + ) + + box_key = "box_gold_double" if frame_style == "gold" else "box_purple" + frame_ph = self.ctx.assets.get_box_photo(box_key, (w, h)) + if frame_ph is not None: + self._photo_refs.append(frame_ph) + self.arena_canvas.create_image(cx, cy, image=frame_ph, anchor="center", tags="fg") + else: + fallback_col = ACCENT_GOLD if frame_style == "gold" else BORDER_COLOR + self.arena_canvas.create_rectangle( + x1, y1, x2, y2, fill="", outline=fallback_col, width=2, tags="fg" + ) + + if status_border: + self.arena_canvas.create_rectangle( + x1 + 3, y1 + 3, x2 - 3, y2 - 3, + fill="", outline=status_border, width=2, tags="fg", + ) + + def _make_goth_photo( + self, + text: str, + size_px: int, + color: str, + max_width: int | None = None, + ) -> ImageTk.PhotoImage | None: + if not text: + return None + try: + kwargs = {"size_px": size_px, "color": color} + if max_width is not None: + kwargs["max_width"] = max_width + ph = self.ctx.assets.get_goth_text_photo(text, **kwargs) + if ph is not None: + self._photo_refs.append(ph) + return ph + except TypeError: + try: + ph = self.ctx.assets.get_goth_text_photo(text, size_px=size_px, color=color) + if ph is not None: + self._photo_refs.append(ph) + return ph + except Exception: + return None + except Exception: + return None + + def _place_goth_photo_or_fallback( + self, + cx: int, + cy: int, + ph: ImageTk.PhotoImage | None, + fallback_text: str, + size_px: int, + color: str, + anchor: str = "center", + ): + if ph is not None: + self.arena_canvas.create_image(cx, cy, image=ph, anchor=anchor, tags="fg") + elif fallback_text: + self.arena_canvas.create_text( + cx, + cy, + text=fallback_text, + font=("Georgia", max(9, size_px - 3), "bold"), + fill=color, + anchor=anchor, + tags="fg", + ) + + def _draw_fanned_cards_on_canvas( + self, + cx: int, + cy: int, photos: list, card_size: tuple[int, int], visible_step: int, - bg_color: str, - max_width: int = 360, - ) -> tk.Canvas: - """Zeichnet Karten überlappend auf ein Canvas (ohne negative Tkinter-pack-Paddings).""" + max_width: int = 340, + highlight_color: str | None = None, + ) -> tuple[int, int, int, int]: cw, ch = card_size n = len(photos) if n <= 0: - return tk.Canvas(parent, width=cw, height=ch, bg=bg_color, highlightthickness=0, bd=0) + return (cx, cy, cx, cy) step = visible_step if n > 1 and (cw + (n - 1) * step) > max_width: - step = max(18, (max_width - cw) // (n - 1)) + step = max(16, (max_width - cw) // (n - 1)) total_w = cw + (n - 1) * step if n > 1 else cw - cv = tk.Canvas(parent, width=total_w, height=ch, bg=bg_color, highlightthickness=0, bd=0) + start_x = cx - total_w // 2 + start_y = cy - ch // 2 + + if highlight_color: + self.arena_canvas.create_rectangle( + start_x - 4, + start_y - 4, + start_x + total_w + 4, + start_y + ch + 4, + outline=highlight_color, + width=2, + tags="fg", + ) + for i, ph in enumerate(photos): - cv.create_image(i * step, 0, image=ph, anchor="nw") - return cv + self.arena_canvas.create_image( + start_x + i * step, start_y, image=ph, anchor="nw", tags="fg" + ) + + return (start_x, start_y, start_x + total_w, start_y + ch) # --------------------------------------------------------- - # AUTO-SAVE & RESUME (nur aktiv während The Devil's Deal!) + # AUTO-SAVE & RESUME / STATE SNAPSHOT # --------------------------------------------------------- - def _persist_state(self): - if not self.devils_locked: - return - state_obj = { + def _build_state_dict(self) -> dict: + return { "bj_account_id": self.bj_account["id"], "devils_locked": self.devils_locked, "active_hand_idx": self.active_hand_idx, @@ -151,11 +318,15 @@ class BlackjackTableView: "last_popup_payload": self._last_popup_payload, "engine": self.engine.to_dict(self.bots), } + + def _persist_state(self): + if not self.devils_locked: + return Database.save_game_state( self.ctx.profile["id"], GAME_FOLDER_ID, self.variant_key, - json.dumps(state_obj), + json.dumps(self._build_state_dict()), ) def _clear_persisted_state(self): @@ -165,7 +336,9 @@ class BlackjackTableView: try: data = json.loads(raw_json) self.bj_account = Database.get_blackjack_account(data["bj_account_id"]) - self.devils_locked = bool(data.get("devils_locked", False) or self.bj_account.get("devils_deal_active", 0)) + self.devils_locked = bool( + data.get("devils_locked", False) or self.bj_account.get("devils_deal_active", 0) + ) self.active_hand_idx = int(data.get("active_hand_idx", 0)) self.turn_step = data.get("turn_step", STEP_ZIEHEN) self.settle_only_mode = bool(data.get("settle_only_mode", False)) @@ -197,7 +370,6 @@ class BlackjackTableView: self._begin_new_table_cycle() elif self.engine.state == "DEALER_TURN": self._render_table(reveal_opponents=True, reveal_dealer=True) - self.status_lbl.configure(text=t("bj_dealer_reveals")) self._turn_job = self.ctx.root.after(BJ_DEALER_DELAY_MS, self._dealer_draw_step) elif self.engine.state == "SHOWDOWN" and self._last_popup_payload: self._render_table(reveal_opponents=True, reveal_dealer=True) @@ -212,12 +384,8 @@ class BlackjackTableView: def _cleanup_and_go(self, nav_callable): if self.devils_locked: return - if self._turn_job: - try: - self.ctx.root.after_cancel(self._turn_job) - except Exception: - pass - self._turn_job = None + ImageButton.close_active_hover_tip() + self._cancel_jobs() if self._result_dialog: self._result_dialog.close_dialog() self._result_dialog = None @@ -225,179 +393,101 @@ class BlackjackTableView: nav_callable() def _on_language_switched(self): + ImageButton.close_active_hover_tip() self._persist_state() self._build_ui() if self.engine.state == "ACTION_LOOP": - self._render_table(reveal_opponents=False, reveal_dealer=False) - if self.active_bot_idx == -1: + if self.active_bot_idx == -1 and 0 <= self.active_hand_idx < len(self.engine.player_hands): self._render_current_tree_step() + self._render_table(reveal_opponents=False, reveal_dealer=False) elif self.engine.state == "DEALER_TURN": self._render_table(reveal_opponents=True, reveal_dealer=True) - self.status_lbl.configure(text=t("bj_dealer_reveals")) elif self.engine.state == "SHOWDOWN" and self._last_popup_payload: self._render_table(reveal_opponents=True, reveal_dealer=True) self._open_result_popup(self._build_localized_popup_data(self._last_popup_payload)) + # --------------------------------------------------------- + # UI AUFBAU (Vollbild-Canvas + Universal-Topbar + Bottom-Bar) + # --------------------------------------------------------- def _build_ui(self): if self._result_dialog: self._result_dialog.close_dialog() self._result_dialog = None - self._last_bg_size = (0, 0) + ImageButton.close_active_hover_tip() + self._cached_table_dims = (0, 0) + self._scaled_table_photo = None self.ctx.root.clear_window(apply_global_bg=True) + self.ctx.refresh_game_progress() self.topbar = self.ctx.build_game_topbar( self.ctx.root, - t(f"variant_{self.variant_key}"), - on_game_menu=lambda: self._cleanup_and_go(lambda: self.on_back_to_menu(self.bj_account["id"])), + stats_endpoint="blackjack", + stats_enabled=not self.devils_locked, on_lang_refresh=self._on_language_switched, locked_exit=self.devils_locked, ) - self.table_frame = tk.Frame( - self.ctx.root, bg=TABLE_BG, padx=14, pady=8, - highlightthickness=1, highlightbackground=ERROR_FG if self.devils_locked else BORDER_COLOR + self.hud_var = tk.StringVar(value="") + self.status_var = tk.StringVar(value="") + + self.bottom_bar = SolitaireBottomBar( + self.ctx.root, self.ctx, self.hud_var, self.status_var ) - self.table_frame.place(relx=0.5, rely=0.535, anchor="center", relwidth=0.96, relheight=0.88) + self.bottom_bar.pack(fill="x", side="bottom", padx=14, pady=(4, 8)) - # Kompakte 3-Spalten-Leiste unten (Links: Tisch- & Regelinfos | Mitte: Eigene Hand | Rechts: Aktionen) - bottom_area = tk.Frame(self.table_frame, bg=TABLE_BG, height=218) - bottom_area.pack(fill="x", side="bottom", pady=(6, 0)) - bottom_area.pack_propagate(False) - - bottom_area.columnconfigure(0, weight=30, uniform="bjcols") - bottom_area.columnconfigure(1, weight=44, uniform="bjcols") - bottom_area.columnconfigure(2, weight=26, uniform="bjcols") - bottom_area.rowconfigure(0, weight=1) - - # Linkes Zusatz-/Status-Panel (verhindert Clipping in der Mitte) - self.left_info_panel = tk.Frame( - bottom_area, bg=PANEL_BG, padx=10, pady=8, - highlightthickness=1, highlightbackground=BORDER_COLOR - ) - self.left_info_panel.grid(row=0, column=0, sticky="nsew", padx=(0, 6)) - - tk.Label( - self.left_info_panel, - text=t(f"variant_{self.variant_key}"), - font=("Helvetica", 10, "bold"), - fg=ACCENT_GOTH, - bg=PANEL_BG, - anchor="w", - ).pack(fill="x") - - tk.Frame(self.left_info_panel, bg=SUBTLE_BORDER, height=1).pack(fill="x", pady=(4, 6)) - - tk.Label( - self.left_info_panel, - text=t("bj_variant_desc", self.cfg["decks"], BJ_INITIAL_ANTE), - font=("Helvetica", 8), - fg=MUTED_FG, - bg=PANEL_BG, - wraplength=280, - justify="left", - anchor="w", - ).pack(fill="x", pady=(0, 8)) - - self.status_lbl = tk.Label( - self.left_info_panel, - text="", - font=("Helvetica", 9, "bold"), - fg=ACCENT_GOLD, - bg=PANEL_BG, - wraplength=280, - justify="left", - anchor="nw", - ) - self.status_lbl.pack(fill="both", expand=True) - - # Mittleres Panel: Nutzer-Hand - center_player_wrap = tk.Frame( - bottom_area, bg=PANEL_BG, padx=10, pady=6, - highlightthickness=1, highlightbackground=SUBTLE_BORDER - ) - center_player_wrap.grid(row=0, column=1, sticky="nsew", padx=4) - - self.player_sec = tk.Frame(center_player_wrap, bg=PANEL_BG) - self.player_sec.pack(fill="both", expand=True) - - # Rechtes Panel: Vertikale Aktions-Buttons direkt neben dem Spieler - self.controls_frame = tk.Frame( - bottom_area, bg=PANEL_BG, padx=8, pady=5, - highlightthickness=1, highlightbackground=BORDER_COLOR - ) - self.controls_frame.grid(row=0, column=2, sticky="nsew", padx=(6, 0)) - - # Canvas für den ovalen Tisch (`poker_table.png`) self.arena_canvas = tk.Canvas( - self.table_frame, bg="#120f18", highlightthickness=1, highlightbackground=SUBTLE_BORDER + self.ctx.root, bg=TABLE_BG, bd=0, highlightthickness=0 ) - self.arena_canvas.pack(fill="both", expand=True) - self.arena_canvas.bind("", self._on_arena_resize) + self.arena_canvas.pack(fill="both", expand=True, padx=14, pady=(4, 2)) + self.arena_canvas.bind("", self._on_arena_configure) - # Bank-Box (oben mittig auf dem Canvas) - felt_bg = "#1b1626" - self.board_box = tk.Frame( - self.arena_canvas, bg=felt_bg, padx=10, pady=5, - highlightthickness=1, highlightbackground=SUBTLE_BORDER - ) - self.board_box.place(relx=0.50, rely=0.25, anchor="center") - - self.dealer_lbl = tk.Label( - self.board_box, text=t("bj_dealer_title"), - font=("Helvetica", 9, "bold"), fg=MUTED_FG, bg=felt_bg - ) - self.dealer_lbl.pack(pady=(0, 3)) - - self.dealer_cards_frame = tk.Frame(self.board_box, bg=felt_bg) - self.dealer_cards_frame.pack() - - # Pot-Ansicht zentral in der Tischmitte (wie auf der Skizze) - self.pot_box = tk.Frame( - self.arena_canvas, bg=PANEL_BG, padx=14, pady=6, - highlightthickness=1, highlightbackground=ACCENT_GOLD - ) - self.pot_box.place(relx=0.50, rely=0.67, anchor="center") - - self.pot_lbl = tk.Label( - self.pot_box, text="", font=("Helvetica", 10, "bold"), - fg=ACCENT_GOLD, bg=PANEL_BG - ) - self.pot_lbl.pack() - - self._bot_seat_frames: list[tk.Frame] = [] self._refresh_header() - def _on_arena_resize(self, event): - w, h = event.width, event.height - if w < 80 or h < 80 or (w, h) == self._last_bg_size: - return - self._last_bg_size = (w, h) + def _set_bottom_buttons( + self, + primary_buttons: list[ImageButton], + overflow_buttons: list[ImageButton] | None = None, + ): + ImageButton.close_active_hover_tip() + if hasattr(self, "bottom_bar") and self.bottom_bar.winfo_exists(): + self.bottom_bar.set_buttons(primary_buttons, overflow_buttons=overflow_buttons) - self.arena_canvas.delete("table_bg") - if self._raw_table_pil is not None: - fitted = self._raw_table_pil.resize((w, h), Image.Resampling.LANCZOS) - self._scaled_table_photo = ImageTk.PhotoImage(fitted) - self.arena_canvas.create_image( - 0, 0, image=self._scaled_table_photo, anchor="nw", tags="table_bg" - ) - self.arena_canvas.tag_lower("table_bg") - else: - mx, my_top, my_bot = int(w * 0.11), int(h * 0.13), int(h * 0.08) - self.arena_canvas.create_oval( - mx, my_top, w - mx, h - my_bot, - fill="#14111b", outline=BORDER_COLOR, width=3, tags="table_bg" + def _on_arena_configure(self, _event=None): + if not self._canvas_alive(): + return + if self._resize_job is not None: + try: + self.ctx.root.after_cancel(self._resize_job) + except Exception: + pass + try: + self._resize_job = self.ctx.root.after( + 35, lambda: self._render_table(*self._last_reveal_state) ) + except Exception: + self._resize_job = None + + def _get_stretched_table_photo(self, exact_w: int, exact_h: int) -> ImageTk.PhotoImage | None: + if self._raw_table_pil is None or exact_w < 160 or exact_h < 120: + return None + if self._scaled_table_photo is None or self._cached_table_dims != (exact_w, exact_h): + stretched = self._raw_table_pil.resize((exact_w, exact_h), Image.Resampling.LANCZOS) + self._scaled_table_photo = ImageTk.PhotoImage(stretched) + self._cached_table_dims = (exact_w, exact_h) + return self._scaled_table_photo def _refresh_header(self): self.bj_account = Database.get_blackjack_account(self.bj_account["id"]) - prof = self.ctx.profile - prog = self.ctx.refresh_game_progress() - self.topbar.extra_label.configure(text=t("bj_header_gold", self.bj_account["account_name"], self.bj_account["gold"])) - self.topbar.level_label.configure( - text=t("level_badge", prof["name"], prog["title"], prog["level"], prog["current_xp"], prog["needed_xp"]) - ) - self.pot_lbl.configure(text=t("bj_pot_banner", self.engine.pot, self.engine.highest_bet)) + self.topbar.update_level_xp_text() + + gold_str = t("bj_header_gold", self.bj_account["account_name"], self.bj_account["gold"]) + hud_segments = [gold_str, f"~Pot: {self.engine.pot}g"] + if self.devils_locked: + hud_segments.append("~Devil's Gambit") + hud_txt = "|".join(hud_segments) + if hasattr(self, "hud_var") and self.hud_var.get() != hud_txt: + self.hud_var.set(hud_txt) # --------------------------------------------------------- # ROUND START @@ -406,6 +496,7 @@ class BlackjackTableView: if self._result_dialog: self._result_dialog.close_dialog() self._result_dialog = None + ImageButton.close_active_hover_tip() self.bj_account = Database.get_blackjack_account(self.bj_account["id"]) self.devils_locked = bool(self.bj_account.get("devils_deal_active", 0)) @@ -418,8 +509,11 @@ class BlackjackTableView: cur_cost = self.ctx.refresh_game_progress()["xp_exchange_cost"] msg = t( "bj_err_not_enough_gold_entry", - self.bj_account["account_name"], GOLD_MIN_TABLE_ENTRY, gold, - cur_cost, XP_TO_GOLD_AMOUNT + self.bj_account["account_name"], + GOLD_MIN_TABLE_ENTRY, + gold, + cur_cost, + XP_TO_GOLD_AMOUNT, ) self._cleanup_and_go(lambda: self.on_back_to_menu(self.bj_account["id"], msg)) return @@ -446,12 +540,16 @@ class BlackjackTableView: self.bot_ai.observe_public_card(self.engine.dealer_hand[0]) self._persist_state() - self._build_ui() + if not self._canvas_alive(): + self._build_ui() + else: + self.topbar.set_locked_exit(self.devils_locked) + self._render_table(reveal_opponents=False, reveal_dealer=False) self._begin_new_table_cycle() # --------------------------------------------------------- - # RENDERING TISCH & SPIELER HÄNDE (Kartenfächer via Canvas) + # CANVAS-LAYOUT: NUR DEALER-KARTEN & POT INNEN, BOTS ECKEN, SPIELER UNTEN # --------------------------------------------------------- @staticmethod def _hand_state_suffix(hand: PlayerHand) -> str: @@ -463,54 +561,108 @@ class BlackjackTableView: return t("bj_state_locked") return "" - def _render_bots(self, reveal_opponents: bool): - for old_f in self._bot_seat_frames: - if old_f.winfo_exists(): - old_f.destroy() - self._bot_seat_frames.clear() + def _draw_dealer_and_pot_inside_table( + self, + table_rect: tuple[int, int, int, int], + player_top_y: int, + reveal_dealer: bool, + ): + """Zeichnet im Tisch-Innenfeld ausschließlich die Dealer-Karten und das kompakte Pot-Banner.""" + tx1, ty1, tx2, ty2 = table_rect + t_cx = (tx1 + tx2) // 2 + t_h = max(260, ty2 - ty1) + + felt_top = ty1 + max(36, int(t_h * 0.15)) + felt_bot = min(ty2 - max(28, int(t_h * 0.12)), player_top_y - 12) + + _dc_w, dc_h = BJ_DEALER_CARD_SIZE + avail_felt_h = max(170, felt_bot - felt_top) + d_cards_cy = felt_top + min(dc_h // 2 + 12, int(avail_felt_h * 0.34)) + + d_photos = [] + for c_idx, card in enumerate(self.engine.dealer_hand): + photo = ( + self.ctx.assets.get_card_back_photo( + color=self.cfg["back_color"], size=BJ_DEALER_CARD_SIZE + ) + if c_idx == 1 and not reveal_dealer + else self.ctx.assets.get_card_photo( + card.image_filename, size=BJ_DEALER_CARD_SIZE + ) + ) + if photo: + self._photo_refs.append(photo) + d_photos.append(photo) + + if d_photos: + self._draw_fanned_cards_on_canvas( + t_cx, d_cards_cy, d_photos, BJ_DEALER_CARD_SIZE, visible_step=38, max_width=340 + ) + + pot_raw = t("bj_pot_banner", self.engine.pot) + pot_txt = pot_raw.split("|")[0].strip() + + pot_cy = min( + felt_bot - 22, + max(d_cards_cy + dc_h // 2 + 34, (d_cards_cy + dc_h // 2 + felt_bot) // 2), + ) + pot_size = max(16, FONT_SIZE_BODY + 1) + pot_ph = self._make_goth_photo(pot_txt, size_px=pot_size, color=FONT_COLOR_TITLE_MAIN) + if pot_ph is not None: + bw = max(230, pot_ph.width() + 64) + bh = max(40, pot_ph.height() + 18) + self._draw_framed_panel(t_cx, pot_cy, bw, bh, frame_style="gold") + self.arena_canvas.create_image(t_cx, pot_cy, image=pot_ph, anchor="center", tags="fg") + else: + self._draw_framed_panel(t_cx, pot_cy, 240, 40, frame_style="gold") + self._place_goth_photo_or_fallback( + t_cx, pot_cy, None, pot_txt, size_px=pot_size, color=ACCENT_GOLD + ) + + def _draw_bots_at_table_corners( + self, + cw: int, + ch: int, + pad_x: int, + pad_top: int, + pad_bot: int, + table_rect: tuple[int, int, int, int], + reveal_opponents: bool, + ): + """Zeichnet die 4 Kultisten-Boxen an den Tischecken mit garantiertem Rahmenabstand.""" + if not self.bots: + return + + tx1, ty1, tx2, ty2 = table_rect + bc_w, bc_h = BJ_BOT_CARD_SIZE + + card_scale = 0.90 if ch < 560 else 1.0 + cur_card_sz = (max(52, int(bc_w * card_scale)), max(76, int(bc_h * card_scale))) + base_box_w = max(198, cur_card_sz[0] + 114) + box_h = cur_card_sz[1] + 90 + + top_cy = max(pad_top + box_h // 2, ty1 + box_h // 2 - 4) + bot_cy = min(ch - pad_bot - box_h // 2, ty2 - box_h // 2 + 22) + if bot_cy - top_cy < box_h + 14: + mid_y = (top_cy + bot_cy) // 2 + top_cy = mid_y - (box_h + 14) // 2 + bot_cy = mid_y + (box_h + 14) // 2 slot_indices = BJ_SEAT_LAYOUT_BY_COUNT.get(len(self.bots), (0, 1, 2, 3)) for bot_i, bot in enumerate(self.bots): coord_idx = slot_indices[bot_i] - rx, ry = BJ_OVAL_BOT_COORDS[coord_idx] + is_left_side = coord_idx in (0, 1) + by = bot_cy if coord_idx in (0, 3) else top_cy is_turn = (bot_i == self.active_bot_idx) - if is_turn: - b_col, thick = ACCENT_GOLD, 2 - elif bot.folded or bot.busted: - b_col, thick = ERROR_FG, 1 - else: - b_col, thick = BORDER_COLOR, 1 - - box = tk.Frame( - self.arena_canvas, bg="#191521", padx=8, pady=4, width=182, - highlightthickness=thick, highlightbackground=b_col - ) - box.place(relx=rx, rely=ry, anchor="center") - self._bot_seat_frames.append(box) + is_out = (bot.folded or bot.busted) + frame_style = "gold" if is_turn else "purple" + status_border = ERROR_FG if is_out else None disp_name = t("bj_bot_rebuy", bot.name) if bot.rebought else bot.name - tk.Label(box, text=disp_name, font=("Helvetica", 9, "bold"), fg=ACCENT_GOTH, bg="#191521").pack() - tk.Label(box, text=t("bj_bot_gold_lbl", bot.gold), font=("Helvetica", 8, "bold"), fg=ACCENT_GOLD, bg="#191521").pack(pady=(1, 2)) - - show_faces = reveal_opponents or bot.busted - bot_photos = [] - for card in bot.hand: - photo = ( - self.ctx.assets.get_card_photo(card.image_filename, size=BJ_BOT_CARD_SIZE) - if show_faces - else self.ctx.assets.get_card_back_photo(color=self.cfg["back_color"], size=BJ_BOT_CARD_SIZE) - ) - if photo: - self._photo_refs.append(photo) - bot_photos.append(photo) - - if bot_photos: - cv = self._create_fanned_cards_canvas( - box, bot_photos, BJ_BOT_CARD_SIZE, visible_step=28, bg_color="#191521", max_width=164 - ) - cv.pack(pady=2) + name_col = ACCENT_GOLD if is_turn else ACCENT_GOTH + gold_txt = t("bj_bot_gold_lbl", bot.gold) if reveal_opponents and bot.hand: b_val, _ = HandEvaluator.evaluate(bot.hand) @@ -527,116 +679,251 @@ class BlackjackTableView: else: info_txt = "" - tk.Label( - box, text=info_txt, font=("Helvetica", 8, "bold" if bot.busted else "normal"), - fg=ERROR_FG if (bot.busted or bot.folded) else FG_COLOR, bg="#191521" - ).pack(pady=(1, 0)) + info_col = ERROR_FG if is_out else FG_COLOR - def _render_player_hands(self): - for w in self.player_sec.winfo_children(): - w.destroy() + name_sz = max(14, FONT_SIZE_BODY - 1) + sub_sz = max(13, FONT_SIZE_BODY - 2) + name_ph = self._make_goth_photo(disp_name, size_px=name_sz, color=name_col, max_width=220) + gold_ph = self._make_goth_photo(gold_txt, size_px=sub_sz, color=ACCENT_GOLD) + info_ph = self._make_goth_photo(info_txt, size_px=sub_sz, color=info_col, max_width=220) + widest_txt = max( + (ph.width() for ph in (name_ph, gold_ph, info_ph) if ph is not None), + default=140, + ) + box_w = max(base_box_w, min(268, widest_txt + 54)) + + if is_left_side: + bx = max(pad_x + box_w // 2, tx1 + int(box_w * 0.36)) + else: + bx = min(cw - pad_x - box_w // 2, tx2 - int(box_w * 0.36)) + + self._draw_framed_panel( + bx, by, box_w, box_h, frame_style=frame_style, status_border=status_border + ) + + top_y = by - box_h // 2 + bot_y = by + box_h // 2 + cards_cy = by + 6 + + self._place_goth_photo_or_fallback(bx, top_y + 23, name_ph, disp_name, name_sz, name_col) + self._place_goth_photo_or_fallback(bx, top_y + 42, gold_ph, gold_txt, sub_sz, ACCENT_GOLD) + + show_faces = reveal_opponents or bot.busted + bot_photos = [] + for card in bot.hand: + photo = ( + self.ctx.assets.get_card_photo(card.image_filename, size=cur_card_sz) + if show_faces + else self.ctx.assets.get_card_back_photo( + color=self.cfg["back_color"], size=cur_card_sz + ) + ) + if photo: + self._photo_refs.append(photo) + bot_photos.append(photo) + + if bot_photos: + self._draw_fanned_cards_on_canvas( + bx, + cards_cy, + bot_photos, + cur_card_sz, + visible_step=25, + max_width=box_w - 36, + ) + + self._place_goth_photo_or_fallback(bx, bot_y - 21, info_ph, info_txt, sub_sz, info_col) + + def _draw_player_below_table(self, cw: int, player_zone_top: int, player_zone_bot: int): + """Zeichnet deine eigene Hand am unteren Tischrand mit dynamischer Boxbreite.""" hands = self.engine.player_hands if not hands: return + avail_h = max(140, player_zone_bot - player_zone_top) + zone_cy = (player_zone_top + player_zone_bot) // 2 + if len(hands) == 1: h = hands[0] + base_w, base_h = PLAYING_CARD_SIZE + max_card_h = max(88, min(base_h, avail_h - 52)) + scale = max_card_h / max(1, base_h) + card_sz = (max(60, int(round(base_w * scale))), int(round(base_h * scale))) + p_photos = [] for card in h.cards: - photo = self.ctx.assets.get_card_photo(card.image_filename, size=PLAYING_CARD_SIZE) + photo = self.ctx.assets.get_card_photo(card.image_filename, size=card_sz) if photo: self._photo_refs.append(photo) p_photos.append(photo) - if p_photos: - cv = self._create_fanned_cards_canvas( - self.player_sec, p_photos, PLAYING_CARD_SIZE, visible_step=38, bg_color=PANEL_BG, max_width=400 - ) - cv.pack(expand=True, pady=(2, 2)) - p_val, p_soft = HandEvaluator.evaluate(h.cards) soft_hint = t("bj_soft_hint", p_val) if p_soft and p_val < 21 else "" suffix = self._hand_state_suffix(h) - lbl_col = ERROR_FG if (h.busted or h.folded) else FG_COLOR - tk.Label( - self.player_sec, - text=t("bj_player_total", p_val, soft_hint, h.bet_in_pot, suffix), - font=("Helvetica", 10, "bold"), fg=lbl_col, bg=PANEL_BG, pady=2 - ).pack(side="bottom", pady=(2, 2)) + lbl_txt = t("bj_player_total", p_val, soft_hint, h.bet_in_pot, suffix) + + is_player_turn = (self.engine.state == "ACTION_LOOP" and self.active_bot_idx == -1) + is_out = (h.busted or h.folded) + lbl_col = ERROR_FG if is_out else FONT_COLOR_TITLE_MAIN + lbl_sz = max(14, FONT_SIZE_BODY - 1) + lbl_ph = self._make_goth_photo(lbl_txt, size_px=lbl_sz, color=lbl_col) + + n_cards = max(1, len(p_photos)) + step = 36 + fan_w = card_sz[0] + max(0, n_cards - 1) * step + txt_w = lbl_ph.width() if lbl_ph is not None else 240 + + box_w = max(300, min(560, max(fan_w + 96, txt_w + 72))) + box_h = min(avail_h, card_sz[1] + 52) + + self._draw_framed_panel( + cw // 2, + zone_cy, + box_w, + box_h, + frame_style="gold" if is_player_turn and not is_out else "purple", + status_border=ERROR_FG if is_out else None, + ) + + cards_cy = zone_cy - 11 + if p_photos: + self._draw_fanned_cards_on_canvas( + cw // 2, + cards_cy, + p_photos, + card_sz, + visible_step=step, + max_width=box_w - 44, + ) + + self._place_goth_photo_or_fallback( + cw // 2, zone_cy + box_h // 2 - 20, lbl_ph, lbl_txt, lbl_sz, lbl_col + ) return - split_wrap = tk.Frame(self.player_sec, bg=PANEL_BG) - split_wrap.pack(expand=True) + # Split-Hände nebeneinander unten + base_w, base_h = BJ_SPLIT_CARD_SIZE + max_card_h = max(80, min(base_h, avail_h - 48)) + scale = max_card_h / max(1, base_h) + card_sz = (max(54, int(round(base_w * scale))), int(round(base_h * scale))) + box_h = min(avail_h, card_sz[1] + 48) + lbl_sz = max(13, FONT_SIZE_BODY - 2) + prepared_splits = [] + max_box_w = 228 for idx, h in enumerate(hands): - is_active = (self.engine.state == "ACTION_LOOP" and self.active_bot_idx == -1 and idx == self.active_hand_idx) - b_col = ACCENT_GOLD if is_active else (ERROR_FG if (h.busted or h.folded) else SUBTLE_BORDER) - hbox = tk.Frame( - split_wrap, bg=CELL_BG, padx=8, pady=4, - highlightthickness=2 if is_active else 1, highlightbackground=b_col + is_active = ( + self.engine.state == "ACTION_LOOP" + and self.active_bot_idx == -1 + and idx == self.active_hand_idx + ) + is_out = (h.busted or h.folded) + p_val, p_soft = HandEvaluator.evaluate(h.cards) + soft_hint = t("bj_soft_hint", p_val) if p_soft and p_val < 21 else "" + suffix = self._hand_state_suffix(h) + lbl_txt = t("bj_hand_box_title", idx + 1, p_val, soft_hint, h.bet_in_pot, suffix) + lbl_col = ACCENT_GOLD if is_active else (ERROR_FG if is_out else FG_COLOR) + lbl_ph = self._make_goth_photo(lbl_txt, size_px=lbl_sz, color=lbl_col) + txt_w = lbl_ph.width() if lbl_ph is not None else 180 + sp_fan_w = card_sz[0] + max(0, len(h.cards) - 1) * 28 + req_w = max(228, min(320, max(sp_fan_w + 64, txt_w + 60))) + max_box_w = max(max_box_w, req_w) + prepared_splits.append((idx, h, is_active, is_out, lbl_txt, lbl_col, lbl_ph)) + + n_hands = len(hands) + slot_gap = max(max_box_w + 14, min(310, (cw - 360) // max(1, n_hands))) + start_cx = cw // 2 - ((n_hands - 1) * slot_gap) // 2 + + for idx, h, is_active, is_out, lbl_txt, lbl_col, lbl_ph in prepared_splits: + h_cx = start_cx + idx * slot_gap + self._draw_framed_panel( + h_cx, + zone_cy, + max_box_w, + box_h, + frame_style="gold" if is_active else "purple", + status_border=ERROR_FG if is_out else None, ) - hbox.pack(side="left", padx=5) sp_photos = [] for card in h.cards: - photo = self.ctx.assets.get_card_photo(card.image_filename, size=BJ_SPLIT_CARD_SIZE) + photo = self.ctx.assets.get_card_photo(card.image_filename, size=card_sz) if photo: self._photo_refs.append(photo) sp_photos.append(photo) if sp_photos: - cv = self._create_fanned_cards_canvas( - hbox, sp_photos, BJ_SPLIT_CARD_SIZE, visible_step=32, bg_color=CELL_BG, max_width=195 + self._draw_fanned_cards_on_canvas( + h_cx, + zone_cy - 10, + sp_photos, + card_sz, + visible_step=28, + max_width=max_box_w - 36, ) - cv.pack(pady=2) - p_val, p_soft = HandEvaluator.evaluate(h.cards) - soft_hint = t("bj_soft_hint", p_val) if p_soft and p_val < 21 else "" - suffix = self._hand_state_suffix(h) - lbl_col = ACCENT_GOLD if is_active else (ERROR_FG if (h.busted or h.folded) else FG_COLOR) - tk.Label( - hbox, - text=t("bj_hand_box_title", idx + 1, p_val, soft_hint, h.bet_in_pot, suffix), - font=("Helvetica", 9, "bold"), fg=lbl_col, bg=CELL_BG, pady=1 - ).pack(pady=(1, 0)) + self._place_goth_photo_or_fallback( + h_cx, zone_cy + box_h // 2 - 18, lbl_ph, lbl_txt, lbl_sz, lbl_col + ) def _render_table(self, reveal_opponents: bool, reveal_dealer: bool): + self._last_reveal_state = (reveal_opponents, reveal_dealer) + if not self._canvas_alive(): + return + + cw = max(760, self.arena_canvas.winfo_width()) + ch = max(460, self.arena_canvas.winfo_height()) + + bg_ids = set(self.arena_canvas.find_withtag("table_bg_slice")) + for item_id in self.arena_canvas.find_all(): + if item_id not in bg_ids: + self.arena_canvas.delete(item_id) self._photo_refs.clear() - for w in self.dealer_cards_frame.winfo_children(): - w.destroy() - felt_bg = "#1b1626" - d_photos = [] - for c_idx, card in enumerate(self.engine.dealer_hand): - photo = ( - self.ctx.assets.get_card_back_photo(color=self.cfg["back_color"], size=BJ_DEALER_CARD_SIZE) - if c_idx == 1 and not reveal_dealer - else self.ctx.assets.get_card_photo(card.image_filename, size=BJ_DEALER_CARD_SIZE) + self._bg_renderer.draw_on_canvas(self.arena_canvas, cw, ch) + + pad_x = max(24, int(cw * 0.022)) + pad_top = 6 + pad_bot = 6 + + player_zone_h = max(152, min(174, int(ch * 0.31))) + player_zone_bot = ch - pad_bot + player_zone_top = player_zone_bot - player_zone_h + + table_top = pad_top + table_bot = min(ch - pad_bot - 60, player_zone_top + 64) + table_h = max(280, table_bot - table_top) + table_w = max(680, cw - 2 * pad_x - 90) + table_cx = cw // 2 + table_cy = table_top + table_h // 2 + table_rect = ( + table_cx - table_w // 2, + table_top, + table_cx + table_w // 2, + table_top + table_h, + ) + + tbl_photo = self._get_stretched_table_photo(table_w, table_h) + if tbl_photo is not None: + self.arena_canvas.create_image( + table_cx, table_cy, image=tbl_photo, anchor="center", tags="fg" ) - if photo: - self._photo_refs.append(photo) - d_photos.append(photo) - - if d_photos: - d_cv = self._create_fanned_cards_canvas( - self.dealer_cards_frame, d_photos, BJ_DEALER_CARD_SIZE, visible_step=36, bg_color=felt_bg, max_width=320 + else: + self.arena_canvas.create_oval( + table_rect[0], table_rect[1], table_rect[2], table_rect[3], + fill="#14111b", outline=BORDER_COLOR, width=3, tags="fg", ) - d_cv.pack() - if not reveal_dealer and self.engine.dealer_hand: - up_val, _ = HandEvaluator.evaluate([self.engine.dealer_hand[0]]) - self.dealer_lbl.configure(text=t("bj_dealer_shows", up_val), bg=felt_bg) - elif self.engine.dealer_hand: - d_val, _ = HandEvaluator.evaluate(self.engine.dealer_hand) - self.dealer_lbl.configure(text=t("bj_dealer_total", d_val), bg=felt_bg) - - self._render_player_hands() - self._render_bots(reveal_opponents=reveal_opponents) + self._draw_dealer_and_pot_inside_table(table_rect, player_zone_top, reveal_dealer) + self._draw_bots_at_table_corners( + cw, ch, pad_x, pad_top, pad_bot, table_rect, reveal_opponents + ) + self._draw_player_below_table(cw, player_zone_top, player_zone_bot) self._refresh_header() # --------------------------------------------------------- - # TISCH-UMLAUF LOGIK + # TISCH-UMLAUF LOGIK & HOVER-HILFE AUF ALLEN AKTIONEN # --------------------------------------------------------- def _begin_new_table_cycle(self): if not self.engine.any_contender_alive(self.bots): @@ -693,8 +980,8 @@ class BlackjackTableView: if to_call > 0: self.turn_step = STEP_MITGEHEN self._persist_state() - self._render_table(reveal_opponents=False, reveal_dealer=False) self._render_current_tree_step() + self._render_table(reveal_opponents=False, reveal_dealer=False) return self.active_hand_idx += 1 continue @@ -702,24 +989,24 @@ class BlackjackTableView: if to_call > 0: self.turn_step = STEP_MITGEHEN self._persist_state() - self._render_table(reveal_opponents=False, reveal_dealer=False) self._render_current_tree_step() + self._render_table(reveal_opponents=False, reveal_dealer=False) return h_val, _ = HandEvaluator.evaluate(h.cards) if not h.cards_locked and not h.doubled and h_val < 21: self.turn_step = STEP_ZIEHEN self._persist_state() - self._render_table(reveal_opponents=False, reveal_dealer=False) self._render_current_tree_step() + self._render_table(reveal_opponents=False, reveal_dealer=False) return dyn_chips = self._get_current_level_chips() if wallet >= dyn_chips[0]: self.turn_step = STEP_ERHOEHEN self._persist_state() - self._render_table(reveal_opponents=False, reveal_dealer=False) self._render_current_tree_step() + self._render_table(reveal_opponents=False, reveal_dealer=False) return self.active_hand_idx += 1 @@ -732,102 +1019,168 @@ class BlackjackTableView: self._step_next_player_hand() def _render_current_tree_step(self): - for w in self.controls_frame.winfo_children(): - w.destroy() - self.bj_account = Database.get_blackjack_account(self.bj_account["id"]) wallet = self.bj_account["gold"] hand = self.engine.player_hands[self.active_hand_idx] - hand_tag = t("bj_active_hand_tag", self.active_hand_idx + 1) if len(self.engine.player_hands) > 1 else "" - col = tk.Frame(self.controls_frame, bg=PANEL_BG) - col.pack(expand=True) + btn_norm = self.ctx.assets.raw_btn_default + btn_purp = self.ctx.assets.raw_btn_purple + btn_fire = self.ctx.assets.raw_btn_fire or btn_purp + + primary_btns: list[ImageButton] = [] + overflow_btns: list[ImageButton] = [] if self.turn_step == STEP_MITGEHEN: raw_deficit = max(0, self.engine.highest_bet - hand.bet_in_pot) to_call = min(wallet, raw_deficit) - self.status_lbl.configure(text=t("bj_tree_step1_call", hand_tag, to_call)) - ImageButton( - col, t("bj_tree_btn_call_yes", to_call), - self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active, - lambda: self._on_step1_call_yes(to_call), - sound_mgr=self.ctx.sounds, width=175, height=30, font=("Helvetica", 9, "bold") - ).pack(pady=3) - - ImageButton( - col, t("bj_tree_btn_call_no_lose"), - self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active, - self._on_fold_hand, - sound_mgr=self.ctx.sounds, width=175, height=30, font=("Helvetica", 9, "bold") - ).pack(pady=3) + primary_btns.append( + ImageButton( + self.bottom_bar, + t("bj_tree_btn_call_yes", to_call), + btn_fire, + btn_fire, + lambda: self._on_step1_call_yes(to_call), + sound_mgr=self.ctx.sounds, + width=162, + height=30, + style="fire", + hover_text=lambda: t("bj_tip_call_yes"), + ) + ) + overflow_btns.append( + ImageButton( + self.bottom_bar, + t("bj_tree_btn_call_no_lose"), + btn_norm, + btn_purp, + self._on_fold_hand, + sound_mgr=self.ctx.sounds, + width=162, + height=30, + style="amethyst", + hover_text=lambda: t("bj_tip_fold"), + ) + ) + self._set_bottom_buttons(primary_btns, overflow_buttons=overflow_btns) return if self.turn_step == STEP_ZIEHEN: - self.status_lbl.configure(text=t("bj_tree_step2_draw", hand_tag)) - - ImageButton( - col, t("bj_tree_btn_draw_yes"), - self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active, - self._on_step2_draw_yes, - sound_mgr=self.ctx.sounds, width=175, height=28, font=("Helvetica", 9, "bold") - ).pack(pady=2) + primary_btns.append( + ImageButton( + self.bottom_bar, + t("bj_tree_btn_draw_yes"), + btn_fire, + btn_fire, + self._on_step2_draw_yes, + sound_mgr=self.ctx.sounds, + width=138, + height=30, + style="fire", + hover_text=lambda: t("bj_tip_draw_yes"), + ) + ) if self.engine.can_double_down(self.active_hand_idx, wallet): dd_cost = self.engine.get_double_down_cost(self.active_hand_idx) - ImageButton( - col, t("bj_double_btn", dd_cost), - self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active, - self._on_step2_double_down, - sound_mgr=self.ctx.sounds, width=175, height=28, font=("Helvetica", 9, "bold") - ).pack(pady=2) + primary_btns.append( + ImageButton( + self.bottom_bar, + t("bj_double_btn", dd_cost), + btn_norm, + btn_purp, + self._on_step2_double_down, + sound_mgr=self.ctx.sounds, + width=132, + height=30, + style="amethyst", + hover_text=lambda: t("bj_tip_double"), + ) + ) if self.engine.can_split_hand(self.active_hand_idx, wallet): sp_cost = self.engine.highest_bet + primary_btns.append( + ImageButton( + self.bottom_bar, + t("bj_split_btn", sp_cost), + btn_norm, + btn_purp, + self._on_step2_split, + sound_mgr=self.ctx.sounds, + width=124, + height=30, + style="amethyst", + hover_text=lambda: t("bj_tip_split"), + ) + ) + + overflow_btns.append( ImageButton( - col, t("bj_split_btn", sp_cost), - self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active, - self._on_step2_split, - sound_mgr=self.ctx.sounds, width=175, height=28, font=("Helvetica", 9, "bold") - ).pack(pady=2) - - ImageButton( - col, t("bj_tree_btn_draw_no"), - self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active, - self._on_step2_draw_no, - sound_mgr=None, width=175, height=28, font=("Helvetica", 9, "bold") - ).pack(pady=2) - - ImageButton( - col, t("bj_fold_btn"), - self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active, - self._on_fold_hand, - sound_mgr=self.ctx.sounds, width=175, height=28, font=("Helvetica", 9, "bold") - ).pack(pady=2) + self.bottom_bar, + t("bj_tree_btn_draw_no"), + btn_norm, + btn_purp, + self._on_step2_draw_no, + sound_mgr=None, + width=134, + height=30, + style="amethyst", + hover_text=lambda: t("bj_tip_draw_no"), + ) + ) + overflow_btns.append( + ImageButton( + self.bottom_bar, + t("bj_fold_btn"), + btn_norm, + btn_purp, + self._on_fold_hand, + sound_mgr=self.ctx.sounds, + width=110, + height=30, + style="amethyst", + hover_text=lambda: t("bj_tip_fold"), + ) + ) + self._set_bottom_buttons(primary_btns, overflow_buttons=overflow_btns) return if self.turn_step == STEP_ERHOEHEN: - self.status_lbl.configure(text=t("bj_tree_step3_raise", hand_tag)) dyn_chips = self._get_current_level_chips() avail_chips = [c for c in dyn_chips if wallet >= c] - if avail_chips: - grid_f = tk.Frame(col, bg=PANEL_BG) - grid_f.pack(pady=(2, 4)) - for idx, chip in enumerate(avail_chips): + for chip in avail_chips: + primary_btns.append( ImageButton( - grid_f, f"+{chip}g", - self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active, + self.bottom_bar, + f"+{chip}g", + btn_fire, + btn_fire, lambda c=chip: self._on_step3_raise_yes(c), - sound_mgr=self.ctx.sounds, width=85, height=28, font=("Helvetica", 9, "bold") - ).grid(row=idx // 2, column=idx % 2, padx=2, pady=2) + sound_mgr=self.ctx.sounds, + width=76, + height=30, + style="fire", + hover_text=lambda: t("bj_tip_raise_chip"), + ) + ) - ImageButton( - col, t("bj_tree_btn_raise_no"), - self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active, - self._on_step3_raise_no, - sound_mgr=self.ctx.sounds, width=175, height=30, font=("Helvetica", 9, "bold") - ).pack(pady=2) + overflow_btns.append( + ImageButton( + self.bottom_bar, + t("bj_tree_btn_raise_no"), + btn_norm, + btn_purp, + self._on_step3_raise_no, + sound_mgr=self.ctx.sounds, + width=162, + height=30, + style="amethyst", + hover_text=lambda: t("bj_tip_raise_no"), + ) + ) + self._set_bottom_buttons(primary_btns, overflow_buttons=overflow_btns) # --------------------------------------------------------- # BUTTON-AKTIONEN SPIELER @@ -845,18 +1198,19 @@ class BlackjackTableView: self.turn_step = STEP_ERHOEHEN self._persist_state() self._render_current_tree_step() + self._render_table(reveal_opponents=False, reveal_dealer=False) else: self._finish_current_hand_turn() def _on_step1_call_yes(self, to_call: int): + ImageButton.close_active_hover_tip() if to_call > 0: paid = self.engine.player_add_gold_to_pot(self.active_hand_idx, to_call) if paid > 0: self.bj_account = Database.update_blackjack_gold(self.bj_account["id"], -paid) - self._render_table(reveal_opponents=False, reveal_dealer=False) - if self.settle_only_mode: + self._render_table(reveal_opponents=False, reveal_dealer=False) self._finish_current_hand_turn() return @@ -866,10 +1220,13 @@ class BlackjackTableView: self.turn_step = STEP_ZIEHEN self._persist_state() self._render_current_tree_step() + self._render_table(reveal_opponents=False, reveal_dealer=False) else: + self._render_table(reveal_opponents=False, reveal_dealer=False) self._advance_to_erhoehen_or_next() def _on_fold_hand(self): + ImageButton.close_active_hover_tip() hand = self.engine.player_hands[self.active_hand_idx] hand.folded = True hand.cards_locked = True @@ -877,6 +1234,7 @@ class BlackjackTableView: self._finish_current_hand_turn() def _on_step2_draw_yes(self): + ImageButton.close_active_hover_tip() hand = self.engine.player_hands[self.active_hand_idx] self.engine.player_draw_card(self.active_hand_idx) @@ -892,10 +1250,12 @@ class BlackjackTableView: self._advance_to_erhoehen_or_next() def _on_step2_draw_no(self): + ImageButton.close_active_hover_tip() self.ctx.sounds.play("stand") self._advance_to_erhoehen_or_next() def _on_step2_double_down(self): + ImageButton.close_active_hover_tip() paid, _card = self.engine.double_down_player_hand(self.active_hand_idx) if paid > 0: self.bj_account = Database.update_blackjack_gold(self.bj_account["id"], -paid) @@ -909,16 +1269,18 @@ class BlackjackTableView: self._finish_current_hand_turn() def _on_step2_split(self): + ImageButton.close_active_hover_tip() paid = self.engine.split_player_hand() if paid > 0: self.bj_account = Database.update_blackjack_gold(self.bj_account["id"], -paid) self.active_hand_idx = 0 self.turn_step = STEP_ZIEHEN self._persist_state() - self._render_table(reveal_opponents=False, reveal_dealer=False) self._render_current_tree_step() + self._render_table(reveal_opponents=False, reveal_dealer=False) def _on_step3_raise_yes(self, chip_amount: int): + ImageButton.close_active_hover_tip() paid = self.engine.player_add_gold_to_pot(self.active_hand_idx, chip_amount) if paid > 0: self.bj_account = Database.update_blackjack_gold(self.bj_account["id"], -paid) @@ -926,14 +1288,14 @@ class BlackjackTableView: self._finish_current_hand_turn() def _on_step3_raise_no(self): + ImageButton.close_active_hover_tip() self._finish_current_hand_turn() # --------------------------------------------------------- # BOT-ZYKLUS IM UMLAUF # --------------------------------------------------------- def _start_bots_cycle(self): - for w in self.controls_frame.winfo_children(): - w.destroy() + self._set_bottom_buttons([]) if not self.bots or not self.engine.any_contender_alive(self.bots): self._on_table_pass_completed() return @@ -942,7 +1304,7 @@ class BlackjackTableView: self._step_next_bot() def _step_next_bot(self): - if not self.table_frame.winfo_exists(): + if not self._canvas_alive(): return while self.active_bot_idx < len(self.bots): @@ -962,12 +1324,13 @@ class BlackjackTableView: bot = self.bots[self.active_bot_idx] self._persist_state() - self.status_lbl.configure(text=t("bj_bot_turn_status", bot.name)) self._render_table(reveal_opponents=False, reveal_dealer=False) - self._turn_job = self.ctx.root.after(BJ_BOT_TURN_DELAY_MS, lambda: self._execute_bot_action(bot)) + self._turn_job = self.ctx.root.after( + BJ_BOT_TURN_DELAY_MS, lambda: self._execute_bot_action(bot) + ) def _execute_bot_action(self, bot: BlackjackBotSeat): - if not self.table_frame.winfo_exists(): + if not self._canvas_alive(): return upcard = self.engine.dealer_hand[0] @@ -995,7 +1358,9 @@ class BlackjackTableView: drew_card = False if not bot.cards_locked and not bot.doubled: - if self.bot_ai.wants_double_down(bot, upcard, self.engine.highest_bet, self.engine.deck.remaining()): + if self.bot_ai.wants_double_down( + bot, upcard, self.engine.highest_bet, self.engine.deck.remaining() + ): dd_cost = max(self.engine.highest_bet, bot.bet_in_pot) * 2 - bot.bet_in_pot paid = self.engine.bot_add_gold_to_pot(bot, dd_cost) self.ctx.sounds.play("click") @@ -1061,14 +1426,18 @@ class BlackjackTableView: return updated_acc = Database.get_blackjack_account(self.bj_account["id"]) - still_only_ten_from_tie = (outcome_type == "TIE" and updated_acc["gold"] == GOLD_MIN_TABLE_ENTRY) + still_only_ten_from_tie = ( + outcome_type == "TIE" and updated_acc["gold"] == GOLD_MIN_TABLE_ENTRY + ) if not still_only_ten_from_tie: Database.set_bj_devils_deal_active(self.bj_account["id"], False) self.devils_locked = False self._clear_persisted_state() - def _award_xp_and_record(self, outcome_type: str, won_stat: bool | None) -> tuple[int, int | None]: + def _award_xp_and_record( + self, outcome_type: str, won_stat: bool | None + ) -> tuple[int, int | None]: duration = max(0.5, time.time() - self.round_start_time) prog_before = self.ctx.refresh_game_progress() opp_levels = [b.ai_level for b in self.bots] @@ -1084,12 +1453,19 @@ class BlackjackTableView: Database.add_game_points(self.ctx.profile["id"], GAME_FOLDER_ID, xp_gained) prog_after = self.ctx.refresh_game_progress() self.ctx.sounds.play("end_battle") - new_lvl = prog_after["level"] if prog_after["level"] > prog_before["level"] else None + new_lvl = ( + prog_after["level"] + if prog_after["level"] > prog_before["level"] + else None + ) return xp_gained, new_lvl old_lvl, new_lvl = self.ctx.record_result( - self.variant_key, won=won_stat, duration_sec=duration, - points_gained=xp_gained, bj_account_id=self.bj_account["id"] + self.variant_key, + won=won_stat, + duration_sec=duration, + points_gained=xp_gained, + bj_account_id=self.bj_account["id"], ) return xp_gained, (new_lvl if new_lvl > old_lvl else None) @@ -1110,7 +1486,9 @@ class BlackjackTableView: return t("bj_rank_split_21") if is_split else t("bj_rank_multi_21", len(cards)) return t("bj_rank_points", val, len(cards)) - def _collect_showdown_snapshot(self, instant_777_winner: str | None = None) -> list[dict]: + def _collect_showdown_snapshot( + self, instant_777_winner: str | None = None + ) -> list[dict]: snapshot: list[dict] = [] d_cards = self.engine.dealer_hand @@ -1130,7 +1508,11 @@ class BlackjackTableView: multi_p = len(self.engine.player_hands) > 1 for idx, h in enumerate(self.engine.player_hands): - hr = self.engine._hand_rank(h.cards, is_split=h.is_split_hand) if h.is_active_in_pot else (0, 0) + hr = ( + self.engine._hand_rank(h.cards, is_split=h.is_split_hand) + if h.is_active_in_pot + else (0, 0) + ) snapshot.append({ "role": "PLAYER", "name": "", @@ -1157,14 +1539,25 @@ class BlackjackTableView: "rank_tuple": list(br), }) - contenders = [s for s in snapshot if s["role"] != "DEALER" and not s["busted"] and not s["folded"]] + contenders = [ + s for s in snapshot + if s["role"] != "DEALER" and not s["busted"] and not s["folded"] + ] dealer_entry = snapshot[0] if instant_777_winner is not None: for s in snapshot: - if instant_777_winner == "PLAYER" and s["role"] == "PLAYER" and s["rank_tuple"] == [3, 21]: + if ( + instant_777_winner == "PLAYER" + and s["role"] == "PLAYER" + and s["rank_tuple"] == [3, 21] + ): s["is_winner"] = True - elif s["role"] == "BOT" and s["name"] == instant_777_winner and s["rank_tuple"] == [3, 21]: + elif ( + s["role"] == "BOT" + and s["name"] == instant_777_winner + and s["rank_tuple"] == [3, 21] + ): s["is_winner"] = True else: s["is_winner"] = False @@ -1186,15 +1579,25 @@ class BlackjackTableView: elif d_rnk == best_contender: dealer_entry["is_winner"] = True for s in snapshot[1:]: - s["is_winner"] = (not s["busted"] and not s["folded"] and tuple(s["rank_tuple"]) == best_contender) + s["is_winner"] = ( + not s["busted"] + and not s["folded"] + and tuple(s["rank_tuple"]) == best_contender + ) else: dealer_entry["is_winner"] = False for s in snapshot[1:]: - s["is_winner"] = (not s["busted"] and not s["folded"] and tuple(s["rank_tuple"]) == best_contender) + s["is_winner"] = ( + not s["busted"] + and not s["folded"] + and tuple(s["rank_tuple"]) == best_contender + ) return snapshot - def _trigger_instant_777_win(self, winner_is_player: bool, winning_bot: BlackjackBotSeat | None): + def _trigger_instant_777_win( + self, winner_is_player: bool, winning_bot: BlackjackBotSeat | None + ): self.engine.state = "SHOWDOWN" self._count_all_table_cards() pot_total = self.engine.pot @@ -1242,15 +1645,14 @@ class BlackjackTableView: self._last_popup_payload = payload if self.devils_locked: self._persist_state() - else: - self._build_ui() - self.status_lbl.configure(text="") + elif self._canvas_alive(): + self.topbar.set_locked_exit(False) + self._render_table(reveal_opponents=True, reveal_dealer=True) self._open_result_popup(self._build_localized_popup_data(payload)) def _start_showdown_and_dealer(self): - for w in self.controls_frame.winfo_children(): - w.destroy() + self._set_bottom_buttons([]) if not self.engine.any_contender_alive(self.bots): self._finalize_showdown() @@ -1258,12 +1660,11 @@ class BlackjackTableView: self.engine.state = "DEALER_TURN" self._persist_state() - self.status_lbl.configure(text=t("bj_dealer_reveals")) self._render_table(reveal_opponents=True, reveal_dealer=True) self._turn_job = self.ctx.root.after(BJ_DEALER_DELAY_MS, self._dealer_draw_step) def _dealer_draw_step(self): - if not self.table_frame.winfo_exists(): + if not self._canvas_alive(): return if self.engine.dealer_should_hit(): self.ctx.sounds.play("click") @@ -1291,12 +1692,16 @@ class BlackjackTableView: snap = self._collect_showdown_snapshot(instant_777_winner=None) if res["player_payout"] > 0: - self.bj_account = Database.update_blackjack_gold(self.bj_account["id"], res["player_payout"]) + self.bj_account = Database.update_blackjack_gold( + self.bj_account["id"], res["player_payout"] + ) w_type = res["winner_type"] if w_type == "PLAYER": has_natural_bj = any( - h.is_active_in_pot and not h.is_split_hand and HandEvaluator.is_natural_blackjack(h.cards) + h.is_active_in_pot + and not h.is_split_hand + and HandEvaluator.is_natural_blackjack(h.cards) for h in self.engine.player_hands ) out_code = "WIN_BJ" if has_natural_bj else "WIN" @@ -1328,9 +1733,9 @@ class BlackjackTableView: self._last_popup_payload = payload if self.devils_locked: self._persist_state() - else: - self._build_ui() - self.status_lbl.configure(text="") + elif self._canvas_alive(): + self.topbar.set_locked_exit(False) + self._render_table(reveal_opponents=True, reveal_dealer=True) self._open_result_popup(self._build_localized_popup_data(payload)) @@ -1356,7 +1761,8 @@ class BlackjackTableView: elif s["role"] == "PLAYER": owner_lbl = ( t("bj_showdown_seat_you_hand", s["hand_no"]) - if s.get("hand_no") else t("bj_showdown_seat_you") + if s.get("hand_no") + else t("bj_showdown_seat_you") ) else: owner_lbl = s["name"] @@ -1391,7 +1797,8 @@ class BlackjackTableView: lvl_to = payload["leveled_to"] lvl_str = ( t("bj_popup_level_up", lvl_to, Progression.get_prestige_title(lvl_to)) - if lvl_to is not None else None + if lvl_to is not None + else None ) cur_gold = Database.get_blackjack_account(self.bj_account["id"])["gold"] @@ -1421,7 +1828,9 @@ class BlackjackTableView: return t("bj_reason_777_win", who) dealer = showdown_hands[0] - contenders = [h for h in showdown_hands[1:] if not h["busted"] and not h["folded"]] + contenders = [ + h for h in showdown_hands[1:] if not h["busted"] and not h["folded"] + ] if not contenders: return t("bj_reason_all_out") @@ -1430,14 +1839,20 @@ class BlackjackTableView: return "" top_rank = winners[0]["rank_tuple"] - winner_names_str = ", ".join(dict.fromkeys(w["owner_label"] for w in winners if not w["is_dealer"])) + winner_names_str = ", ".join( + dict.fromkeys(w["owner_label"] for w in winners if not w["is_dealer"]) + ) if dealer["is_winner"] and len(winners) > 1: return t("bj_reason_dealer_tie_push", dealer["rank_label"]) losers_with_21 = [ - h for h in showdown_hands - if not h["is_winner"] and not h["busted"] and not h["folded"] and h["rank_tuple"][1] == 21 + h + for h in showdown_hands + if not h["is_winner"] + and not h["busted"] + and not h["folded"] + and h["rank_tuple"][1] == 21 ] win_label = dealer["owner_label"] if dealer["is_winner"] else winner_names_str if top_rank == (3, 21) and losers_with_21: @@ -1447,13 +1862,23 @@ class BlackjackTableView: non_dealer_winners = [w for w in winners if not w["is_dealer"]] if len(non_dealer_winners) > 1: - return t("bj_reason_split_pot", non_dealer_winners[0]["rank_label"], winner_names_str) + return t( + "bj_reason_split_pot", + non_dealer_winners[0]["rank_label"], + winner_names_str, + ) if dealer["busted"] and not dealer["is_winner"]: - return t("bj_reason_dealer_bust", dealer["rank_label"], win_label, winners[0]["rank_label"]) + return t( + "bj_reason_dealer_bust", + dealer["rank_label"], + win_label, + winners[0]["rank_label"], + ) others_alive = [ - h for h in showdown_hands + h + for h in showdown_hands if not h["is_winner"] and not h["busted"] and not h["folded"] ] if others_alive: @@ -1462,17 +1887,20 @@ class BlackjackTableView: else: runner_desc = f"{dealer['owner_label']}: {dealer['rank_label']}" - return t("bj_reason_higher_score", win_label, winners[0]["rank_label"], runner_desc) + return t( + "bj_reason_higher_score", win_label, winners[0]["rank_label"], runner_desc + ) def _open_result_popup(self, popup_data: dict): - for w in self.controls_frame.winfo_children(): - w.destroy() + self._set_bottom_buttons([]) self._result_dialog = BlackjackResultDialog( - parent=self.table_frame, + parent=self.arena_canvas, assets=self.ctx.assets, sounds=self.ctx.sounds, result_data=popup_data, on_next_round=self._start_new_round, - on_back_to_menu=lambda: self._cleanup_and_go(lambda: self.on_back_to_menu(self.bj_account["id"])), + on_back_to_menu=lambda: self._cleanup_and_go( + lambda: self.on_back_to_menu(self.bj_account["id"]) + ), ) \ No newline at end of file diff --git a/games/poker/views/__pycache__/poker_table_view.cpython-311.pyc b/games/poker/views/__pycache__/poker_table_view.cpython-311.pyc index e778e85..d76db7f 100644 Binary files a/games/poker/views/__pycache__/poker_table_view.cpython-311.pyc and b/games/poker/views/__pycache__/poker_table_view.cpython-311.pyc differ diff --git a/games/poker/views/poker_hands_overlay.py b/games/poker/views/poker_hands_overlay.py new file mode 100644 index 0000000..cfb9612 --- /dev/null +++ b/games/poker/views/poker_hands_overlay.py @@ -0,0 +1,178 @@ +# -*- coding: utf-8 -*- +# games/poker/views/poker_hands_overlay.py +from __future__ import annotations + +import tkinter as tk +from PIL import Image, ImageTk + +from resources.code_res.game_constants import ( + ACCENT_GOLD, + BG_COLOR, + FG_COLOR, + FONT_COLOR_BODY_MUTED, + FONT_COLOR_TITLE_MAIN, + FONT_SIZE_HEADING, + RED_SUITS, + SUIT_SYMBOLS, +) +from resources.code_res.i18n import t +from view.widgets.image_button import ImageButton + +HAND_REFERENCE_EXAMPLES = ( + (1, 9, (("A", "S"), ("K", "S"), ("Q", "S"), ("J", "S"), ("10", "S"))), + (2, 8, (("J", "S"), ("10", "S"), ("9", "S"), ("8", "S"), ("7", "S"))), + (3, 7, (("K", "H"), ("K", "C"), ("K", "D"), ("K", "S"), None)), + (4, 6, (("A", "H"), ("A", "C"), ("A", "D"), ("9", "S"), ("9", "H"))), + (5, 5, (("K", "S"), ("J", "S"), ("8", "S"), ("7", "S"), ("5", "S"))), + (6, 4, (("J", "H"), ("10", "C"), ("9", "D"), ("8", "S"), ("7", "H"))), + (7, 3, (("K", "H"), ("K", "C"), ("K", "D"), None, None)), + (8, 2, (("A", "H"), ("A", "C"), ("9", "D"), ("9", "S"), None)), + (9, 1, (("K", "H"), ("K", "C"), None, None, None)), + (10, 0, (("A", "H"), None, None, None, None)), +) + + +class PokerHandsOverlay(tk.Canvas): + """Neutrale Kartenreferenz-Übersicht der 10 Poker-Hände (ohne Spoiler der eigenen Hand).""" + + OVL_W = 800 + OVL_H = 468 + + def __init__(self, parent, ctx, on_close): + super().__init__( + parent, + width=self.OVL_W, + height=self.OVL_H, + bg=BG_COLOR, + bd=0, + highlightthickness=0, + ) + self.ctx = ctx + self.assets = ctx.assets + self.on_close = on_close + self._photo_refs: list = [] + + self.place(relx=0.5, rely=0.5, anchor="center") + tk.Widget.tkraise(self) + self._build_content() + + def _draw_mini_cards(self, x0: int, y0: int, cards_spec: tuple): + cw, ch, gap = 22, 26, 3 + for i, spec in enumerate(cards_spec): + cx = x0 + i * (cw + gap) + if spec is None: + self.create_rectangle( + cx, y0, cx + cw, y0 + ch, + fill="#261321", outline="#4e2942", width=1, + ) + else: + rank, suit = spec + fg_col = "#cf3848" if suit in RED_SUITS else "#181421" + sym = SUIT_SYMBOLS.get(suit, suit) + self.create_rectangle( + cx, y0, cx + cw, y0 + ch, + fill="#ede8f5", outline="#8e82a6", width=1, + ) + self.create_text( + cx + cw // 2, y0 + 8, + text=rank, font=("Helvetica", 7, "bold"), fill=fg_col, + ) + self.create_text( + cx + cw // 2, y0 + 18, + text=sym, font=("Helvetica", 8, "bold"), fill=fg_col, + ) + + def _build_content(self): + w, h = self.OVL_W, self.OVL_H + bg_src = self.assets.raw_bg_horizontal or self.assets.raw_bg_vertical or self.assets.raw_bg + if bg_src is not None: + bg_ph = ImageTk.PhotoImage(bg_src.resize((w, h), Image.Resampling.BILINEAR)) + self._photo_refs.append(bg_ph) + self.create_image(0, 0, image=bg_ph, anchor="nw") + + outer = self.assets.get_box_photo("box_big", (w - 6, h - 6)) + if outer: + self._photo_refs.append(outer) + self.create_image(w // 2, h // 2, image=outer, anchor="center") + + hdr_ph = self.assets.get_goth_text_photo( + t("pk_help_header"), + size_px=FONT_SIZE_HEADING, + color=FONT_COLOR_TITLE_MAIN, + align="center", + ) + self._photo_refs.append(hdr_ph) + self.create_image(w // 2, 32, image=hdr_ph, anchor="center") + + self.create_text( + w // 2, + 60, + text=t("pk_help_general_info"), + font=("Helvetica", 9), + fill=FONT_COLOR_BODY_MUTED, + width=w - 80, + justify="center", + anchor="center", + ) + + col_w = (w - 76) // 2 + row_h = 62 + start_y = 86 + + cell_box_purp = self.assets.get_box_photo("box_purple", (col_w, row_h - 4)) + if cell_box_purp: + self._photo_refs.append(cell_box_purp) + + for rank_no, cat_id, cards_spec in HAND_REFERENCE_EXAMPLES: + col_idx = 0 if rank_no <= 5 else 1 + row_idx = (rank_no - 1) % 5 + cx = 30 + col_idx * (col_w + 16) + col_w // 2 + cy = start_y + row_idx * row_h + (row_h - 4) // 2 + left_edge = cx - col_w // 2 + + if cell_box_purp: + self.create_image(cx, cy, image=cell_box_purp, anchor="center") + + self._draw_mini_cards(left_edge + 14, cy - 13, cards_spec) + + raw_name = t(f"pk_hand_{cat_id}").replace("★ ", "").replace(" ★", "") + short_name = raw_name.split(" (")[0] + name_col = ACCENT_GOLD if rank_no == 1 else FG_COLOR + + tip_raw = t(f"pk_help_hand_{cat_id}") + tip_short = tip_raw.split(":", 1)[-1].strip() if ":" in tip_raw else tip_raw + + txt_x = left_edge + 142 + txt_max_w = col_w - 154 + + self.create_text( + txt_x, + cy - 12, + text=f"{rank_no}. {short_name}", + font=("Helvetica", 9, "bold"), + fill=name_col, + anchor="w", + ) + self.create_text( + txt_x, + cy + 9, + text=tip_short, + font=("Helvetica", 8), + fill=FONT_COLOR_BODY_MUTED, + width=txt_max_w, + anchor="w", + ) + + btn_fire = self.assets.raw_btn_fire or self.assets.raw_btn_purple + close_btn = ImageButton( + self, + t("pk_btn_close_help"), + btn_fire, + btn_fire, + self.on_close, + sound_mgr=self.ctx.sounds, + width=156, + height=34, + style="fire", + ) + self.create_window(w // 2, h - 30, window=close_btn, anchor="center") \ No newline at end of file diff --git a/games/poker/views/poker_table_view.py b/games/poker/views/poker_table_view.py index a6575d9..39cb942 100644 --- a/games/poker/views/poker_table_view.py +++ b/games/poker/views/poker_table_view.py @@ -1,5 +1,7 @@ # -*- coding: utf-8 -*- # games/poker/views/poker_table_view.py +from __future__ import annotations + import json import time from pathlib import Path @@ -10,32 +12,38 @@ from games.poker.models.poker_bot_ai import PokerBotAI from games.poker.models.poker_engine import PokerEngine from games.poker.models.poker_evaluator import PokerEvaluator from games.poker.models.poker_seat import PokerSeat +from games.poker.views.poker_hands_overlay import PokerHandsOverlay from games.poker.views.poker_result_dialog import PokerResultDialog +from games.solitaire.base.solitaire_bottom_bar import SolitaireBottomBar +from games.solitaire.base.solitaire_theme import SolitaireTableBgRenderer from models.database import Database from models.progression import Progression from resources.code_res.game_constants import ( - ACCENT_GOLD, ACCENT_GOTH, BORDER_COLOR, CELL_BG, ERROR_FG, - FG_COLOR, MUTED_FG, PANEL_BG, PK_BOT_TURN_DELAY_MS, - PK_STARTING_GOLD, PK_STREET_DELAY_MS, PK_TABLE_IMAGE, - PK_VARIANTS, PLAYING_CARD_SIZE, RED_SUITS, SUBTLE_BORDER, - SUIT_SYMBOLS, TABLE_BG, XP_TO_GOLD_AMOUNT + ACCENT_GOLD, + ACCENT_GOTH, + BORDER_COLOR, + ERROR_FG, + FG_COLOR, + FONT_COLOR_TITLE_MAIN, + FONT_SIZE_BODY, + MUTED_FG, + PK_BOT_TURN_DELAY_MS, + PK_STARTING_GOLD, + PK_STREET_DELAY_MS, + PK_TABLE_IMAGE, + PK_VARIANTS, + PLAYING_CARD_SIZE, + SUBTLE_BORDER, + TABLE_BG, + XP_TO_GOLD_AMOUNT, ) -from resources.code_res.i18n import get_lang, t +from resources.code_res.i18n import t from view.widgets.image_button import ImageButton -from view.widgets.info_badge import InfoBadge GAME_FOLDER_ID = "poker" IMAGES_DIR = Path(__file__).resolve().parents[3] / "resources" / "images" -PK_OVAL_BOARD_CARD = (76, 112) - -OVAL_BOT_COORDS = ( - (0.155, 0.77), # Platz 1: Unten links - (0.155, 0.23), # Platz 2: Oben links - (0.500, 0.14), # Platz 3: Oben Mitte - (0.845, 0.23), # Platz 4: Oben rechts - (0.845, 0.77), # Platz 5: Unten rechts -) +PK_OVAL_BOARD_CARD = (78, 114) SEAT_LAYOUT_BY_COUNT = { 1: (2,), @@ -45,19 +53,6 @@ SEAT_LAYOUT_BY_COUNT = { 5: (0, 1, 2, 3, 4), } -HAND_REFERENCE_EXAMPLES = ( - (1, 9, (("A", "S"), ("K", "S"), ("Q", "S"), ("J", "S"), ("10", "S"))), - (2, 8, (("J", "S"), ("10", "S"), ("9", "S"), ("8", "S"), ("7", "S"))), - (3, 7, (("K", "H"), ("K", "C"), ("K", "D"), ("K", "S"), None)), - (4, 6, (("A", "H"), ("A", "C"), ("A", "D"), ("9", "S"), ("9", "H"))), - (5, 5, (("K", "S"), ("J", "S"), ("8", "S"), ("7", "S"), ("5", "S"))), - (6, 4, (("J", "H"), ("10", "C"), ("9", "D"), ("8", "S"), ("7", "H"))), - (7, 3, (("K", "H"), ("K", "C"), ("K", "D"), None, None)), - (8, 2, (("A", "H"), ("A", "C"), ("9", "D"), ("9", "S"), None)), - (9, 1, (("K", "H"), ("K", "C"), None, None, None)), - (10, 0, (("A", "H"), None, None, None, None)), -) - class PokerTableView: def __init__( @@ -79,12 +74,19 @@ class PokerTableView: self.round_start_time: float = time.time() self._last_popup_payload: dict | None = None self._result_dialog: PokerResultDialog | None = None - self._photo_refs = [] - self._turn_job = None + self._hands_overlay: PokerHandsOverlay | None = None + self._card_ref_btn: ImageButton | None = None + self._photo_refs: list = [] + self._turn_job: str | None = None + self._resize_job: str | None = None + + self._bg_renderer = SolitaireTableBgRenderer(self.ctx.assets.res) self._raw_table_pil: Image.Image | None = self._load_raw_table_image() + self._raw_box_bg_pil: Image.Image | None = self._load_raw_box_bg_image() self._scaled_table_photo: ImageTk.PhotoImage | None = None - self._last_bg_size: tuple[int, int] = (0, 0) + self._cached_table_dims: tuple[int, int] = (0, 0) + self._box_bg_cache: dict[tuple[int, int], ImageTk.PhotoImage] = {} self.ctx.sounds.play_ingame_music() @@ -98,11 +100,22 @@ class PokerTableView: bot_bankroll = max(PK_STARTING_GOLD, level_chips[-1] * 6) self.engine.seats = [ - PokerSeat(seat_id=0, name=self.ctx.profile["name"], is_human=True, stack=self.pk_account["gold"]) + PokerSeat( + seat_id=0, + name=self.ctx.profile["name"], + is_human=True, + stack=self.pk_account["gold"], + ) ] for idx, (lvl, b_name) in enumerate(bot_configs, start=1): self.engine.seats.append( - PokerSeat(seat_id=idx, name=b_name, is_human=False, ai_level=lvl, stack=bot_bankroll) + PokerSeat( + seat_id=idx, + name=b_name, + is_human=False, + ai_level=lvl, + stack=bot_bankroll, + ) ) self._build_ui() @@ -113,11 +126,168 @@ class PokerTableView: img_path = IMAGES_DIR / PK_TABLE_IMAGE if img_path.is_file(): try: - return Image.open(img_path).convert("RGB") + return Image.open(img_path).convert("RGBA") except Exception: return None return None + @staticmethod + def _load_raw_box_bg_image() -> Image.Image | None: + for fname in ("box_background.png", "box_background.jpg"): + p = IMAGES_DIR / fname + if p.is_file(): + try: + return Image.open(p).convert("RGBA") + except Exception: + pass + return None + + def _canvas_alive(self) -> bool: + try: + return hasattr(self, "arena_canvas") and bool(self.arena_canvas.winfo_exists()) + except Exception: + return False + + def _cancel_jobs(self): + for job in (self._turn_job, self._resize_job): + if job is not None: + try: + self.ctx.root.after_cancel(job) + except Exception: + pass + self._turn_job = None + self._resize_job = None + + def _close_hands_overlay(self): + if self._hands_overlay is not None: + try: + if self._hands_overlay.winfo_exists(): + self._hands_overlay.destroy() + except Exception: + pass + self._hands_overlay = None + + def _toggle_hands_overlay(self): + if self._hands_overlay is not None and self._hands_overlay.winfo_exists(): + self._close_hands_overlay() + return + if self._canvas_alive(): + self._hands_overlay = PokerHandsOverlay( + self.arena_canvas, + self.ctx, + on_close=self._close_hands_overlay, + ) + + def _get_box_bg_photo(self, w: int, h: int) -> ImageTk.PhotoImage | None: + if self._raw_box_bg_pil is None or w < 16 or h < 16: + return None + key = (w, h) + cached = self._box_bg_cache.get(key) + if cached is not None: + return cached + if len(self._box_bg_cache) > 24: + self._box_bg_cache.clear() + scaled = self._raw_box_bg_pil.resize((w, h), Image.Resampling.LANCZOS) + ph = ImageTk.PhotoImage(scaled) + self._box_bg_cache[key] = ph + return ph + + def _draw_framed_panel( + self, + cx: int, + cy: int, + w: int, + h: int, + frame_style: str = "purple", + status_border: str | None = None, + ): + x1, y1 = cx - w // 2, cy - h // 2 + x2, y2 = x1 + w, y1 + h + + inset = 5 + inner_w, inner_h = max(16, w - 2 * inset), max(16, h - 2 * inset) + if hasattr(self.ctx.assets, "get_box_bg_photo"): + bg_ph = self.ctx.assets.get_box_bg_photo((inner_w, inner_h)) + else: + bg_ph = self._get_box_bg_photo(inner_w, inner_h) + + if bg_ph is not None: + self._photo_refs.append(bg_ph) + self.arena_canvas.create_image(cx, cy, image=bg_ph, anchor="center", tags="fg") + else: + self.arena_canvas.create_rectangle( + x1 + inset, y1 + inset, x2 - inset, y2 - inset, + fill="#110e18", outline="", tags="fg", + ) + + box_key = "box_gold_double" if frame_style == "gold" else "box_purple" + frame_ph = self.ctx.assets.get_box_photo(box_key, (w, h)) + if frame_ph is not None: + self._photo_refs.append(frame_ph) + self.arena_canvas.create_image(cx, cy, image=frame_ph, anchor="center", tags="fg") + else: + fallback_col = ACCENT_GOLD if frame_style == "gold" else BORDER_COLOR + self.arena_canvas.create_rectangle( + x1, y1, x2, y2, fill="", outline=fallback_col, width=2, tags="fg" + ) + + if status_border: + self.arena_canvas.create_rectangle( + x1 + 3, y1 + 3, x2 - 3, y2 - 3, + fill="", outline=status_border, width=2, tags="fg", + ) + + def _make_goth_photo( + self, + text: str, + size_px: int, + color: str, + max_width: int | None = None, + ) -> ImageTk.PhotoImage | None: + if not text: + return None + try: + kwargs = {"size_px": size_px, "color": color} + if max_width is not None: + kwargs["max_width"] = max_width + ph = self.ctx.assets.get_goth_text_photo(text, **kwargs) + if ph is not None: + self._photo_refs.append(ph) + return ph + except TypeError: + try: + ph = self.ctx.assets.get_goth_text_photo(text, size_px=size_px, color=color) + if ph is not None: + self._photo_refs.append(ph) + return ph + except Exception: + return None + except Exception: + return None + + def _place_goth_photo_or_fallback( + self, + cx: int, + cy: int, + ph: ImageTk.PhotoImage | None, + fallback_text: str, + size_px: int, + color: str, + anchor: str = "center", + ): + if ph is not None: + self.arena_canvas.create_image(cx, cy, image=ph, anchor=anchor, tags="fg") + elif fallback_text: + self.arena_canvas.create_text( + cx, + cy, + text=fallback_text, + font=("Georgia", max(9, size_px - 3), "bold"), + fill=color, + anchor=anchor, + tags="fg", + ) + # --------------------------------------------------------- # AUTO-SAVE & RESUME (nur bei aktivem Devil's Deal!) # --------------------------------------------------------- @@ -145,7 +315,9 @@ class PokerTableView: try: data = json.loads(raw_json) self.pk_account = Database.get_poker_account(data["pk_account_id"]) - self.devils_locked = bool(data.get("devils_locked", False) or self.pk_account.get("devils_deal_active", 0)) + self.devils_locked = bool( + data.get("devils_locked", False) or self.pk_account.get("devils_deal_active", 0) + ) self.round_start_time = time.time() - float(data.get("elapsed_sec", 0.0)) self._last_popup_payload = data.get("last_popup_payload") self.engine.load_from_dict(data["engine"]) @@ -156,8 +328,19 @@ class PokerTableView: self.pk_account = dev_acc or accounts[0] self.devils_locked = bool(self.pk_account.get("devils_deal_active", 0)) self.engine.seats = [ - PokerSeat(seat_id=0, name=self.ctx.profile["name"], is_human=True, stack=self.pk_account["gold"]), - PokerSeat(seat_id=1, name=t("bot_default_name", 1), is_human=False, ai_level=2, stack=PK_STARTING_GOLD), + PokerSeat( + seat_id=0, + name=self.ctx.profile["name"], + is_human=True, + stack=self.pk_account["gold"], + ), + PokerSeat( + seat_id=1, + name=t("bot_default_name", 1), + is_human=False, + ai_level=2, + stack=PK_STARTING_GOLD, + ), ] self._build_ui() self._start_new_hand() @@ -178,13 +361,9 @@ class PokerTableView: def _cleanup_and_go(self, nav_callable): if self.devils_locked: return - InfoBadge.close_global_tip() - if self._turn_job: - try: - self.ctx.root.after_cancel(self._turn_job) - except Exception: - pass - self._turn_job = None + ImageButton.close_active_hover_tip() + self._close_hands_overlay() + self._cancel_jobs() if self._result_dialog: self._result_dialog.close_dialog() self._result_dialog = None @@ -192,7 +371,11 @@ class PokerTableView: nav_callable() def _on_language_switched(self): - InfoBadge.close_global_tip() + was_help_open = ( + self._hands_overlay is not None and self._hands_overlay.winfo_exists() + ) + ImageButton.close_active_hover_tip() + self._close_hands_overlay() self._persist_state() self._build_ui() if self.engine.street == "SHOWDOWN" and self._last_popup_payload: @@ -202,246 +385,120 @@ class PokerTableView: self._render_table() if self.engine.turn_pos == 0 and self.engine.human_seat.can_act: self._show_human_controls() + else: + self._render_waiting_controls() + if was_help_open: + self._toggle_hands_overlay() # --------------------------------------------------------- - # UI AUFBAU MIT STATISCHER BEISPIEL-HILFE & INFO-BADGES + # UI AUFBAU (Vollbild-Canvas + Universal-Topbar + Bottom-Bar) # --------------------------------------------------------- def _build_ui(self): if self._result_dialog: self._result_dialog.close_dialog() self._result_dialog = None + self._close_hands_overlay() - InfoBadge.close_global_tip() - self._last_bg_size = (0, 0) + self._cached_table_dims = (0, 0) + self._scaled_table_photo = None self.ctx.root.clear_window(apply_global_bg=True) + self.ctx.refresh_game_progress() self.topbar = self.ctx.build_game_topbar( self.ctx.root, - t(f"variant_{self.variant_key}"), - on_game_menu=lambda: self._cleanup_and_go(lambda: self.on_back_to_menu(self.pk_account["id"])), + stats_endpoint="poker", + stats_enabled=not self.devils_locked, on_lang_refresh=self._on_language_switched, locked_exit=self.devils_locked, ) - self.table_frame = tk.Frame( - self.ctx.root, bg=TABLE_BG, padx=14, pady=8, - highlightthickness=1, highlightbackground=ERROR_FG if self.devils_locked else BORDER_COLOR + self.hud_var = tk.StringVar(value="") + self.status_var = tk.StringVar(value="") + + self.bottom_bar = SolitaireBottomBar( + self.ctx.root, self.ctx, self.hud_var, self.status_var ) - self.table_frame.place(relx=0.5, rely=0.535, anchor="center", relwidth=0.96, relheight=0.88) - - self.pot_lbl = tk.Label( - self.table_frame, text="", font=("Georgia", 11, "bold"), - fg=ACCENT_GOLD, bg=PANEL_BG, pady=4, highlightthickness=1, highlightbackground=SUBTLE_BORDER - ) - self.pot_lbl.pack(fill="x", side="top", pady=(0, 4)) - - bottom_area = tk.Frame(self.table_frame, bg=TABLE_BG, height=244) - bottom_area.pack(fill="x", side="bottom", pady=(6, 0)) - bottom_area.pack_propagate(False) - - bottom_area.columnconfigure(0, weight=34, uniform="bcols") - bottom_area.columnconfigure(1, weight=39, uniform="bcols") - bottom_area.columnconfigure(2, weight=27, uniform="bcols") - bottom_area.rowconfigure(0, weight=1) - - self.help_panel = tk.Frame( - bottom_area, bg=PANEL_BG, padx=8, pady=5, - highlightthickness=1, highlightbackground=BORDER_COLOR - ) - self.help_panel.grid(row=0, column=0, sticky="nsew", padx=(0, 6)) - self._populate_static_hand_examples() - - center_player_wrap = tk.Frame( - bottom_area, bg=PANEL_BG, padx=10, pady=6, - highlightthickness=1, highlightbackground=SUBTLE_BORDER - ) - center_player_wrap.grid(row=0, column=1, sticky="nsew", padx=4) - - self.status_lbl = tk.Label( - center_player_wrap, text="", font=("Georgia", 10, "bold"), - fg=ACCENT_GOLD, bg=PANEL_BG, wraplength=410, justify="center" - ) - self.status_lbl.pack(side="top", pady=(0, 3)) - - self.player_sec = tk.Frame(center_player_wrap, bg=PANEL_BG) - self.player_sec.pack(fill="both", expand=True) - - self.controls_frame = tk.Frame( - bottom_area, bg=PANEL_BG, padx=8, pady=5, - highlightthickness=1, highlightbackground=BORDER_COLOR - ) - self.controls_frame.grid(row=0, column=2, sticky="nsew", padx=(6, 0)) + self.bottom_bar.pack(fill="x", side="bottom", padx=14, pady=(4, 8)) self.arena_canvas = tk.Canvas( - self.table_frame, bg="#120f18", highlightthickness=1, highlightbackground=SUBTLE_BORDER + self.ctx.root, bg=TABLE_BG, bd=0, highlightthickness=0 ) - self.arena_canvas.pack(fill="both", expand=True) - self.arena_canvas.bind("", self._on_arena_resize) + self.arena_canvas.pack(fill="both", expand=True, padx=14, pady=(4, 2)) + self.arena_canvas.bind("", self._on_arena_configure) - felt_bg = "#1b1626" - self.board_box = tk.Frame( - self.arena_canvas, bg=felt_bg, padx=10, pady=6, - highlightthickness=1, highlightbackground=SUBTLE_BORDER + self._card_ref_btn = ImageButton( + self.arena_canvas, + t("pk_btn_hands_help"), + self.ctx.assets.raw_btn_default, + self.ctx.assets.raw_btn_purple, + self._toggle_hands_overlay, + sound_mgr=self.ctx.sounds, + width=136, + height=34, + style="amethyst", + hover_text=lambda: t("pk_help_general_info"), ) - self.board_box.place(relx=0.5, rely=0.52, anchor="center") - tk.Label( - self.board_box, text=t("pk_board_title"), - font=("Georgia", 9, "bold"), fg=MUTED_FG, bg=felt_bg - ).pack(pady=(0, 3)) - - self.board_cards_frame = tk.Frame(self.board_box, bg=felt_bg, height=PK_OVAL_BOARD_CARD[1] + 2) - self.board_cards_frame.pack() - - self._bot_seat_frames: list[tk.Frame] = [] self._refresh_header() - # --------------------------------------------------------- - # STATISCHE POKER-HÄNDE-TAFEL MIT MINI-BEISPIELKARTEN & ⓘ - # --------------------------------------------------------- - @staticmethod - def _draw_mini_example_strip(parent, cards_spec: tuple) -> tk.Canvas: - cw, ch, gap = 21, 23, 2 - total_w = 5 * cw + 4 * gap - cv = tk.Canvas(parent, width=total_w, height=ch, bg=PANEL_BG, highlightthickness=0) + def _set_bottom_buttons( + self, + primary_buttons: list[ImageButton], + overflow_buttons: list[ImageButton] | None = None, + ): + ImageButton.close_active_hover_tip() + if hasattr(self, "bottom_bar") and self.bottom_bar.winfo_exists(): + self.bottom_bar.set_buttons(primary_buttons, overflow_buttons=overflow_buttons) - for i, spec in enumerate(cards_spec): - x0 = i * (cw + gap) - if spec is None: - cv.create_rectangle( - x0, 1, x0 + cw - 1, ch - 1, - fill="#3a1722", outline="#5c2838", width=1 - ) - else: - rank, suit = spec - is_red = suit in RED_SUITS - fg_col = "#d93848" if is_red else "#1c1824" - sym = SUIT_SYMBOLS.get(suit, suit) - - cv.create_rectangle( - x0, 1, x0 + cw - 1, ch - 1, - fill="#ede8f5", outline="#8e82a6", width=1 - ) - cv.create_text( - x0 + cw // 2, 7, - text=rank, font=("Helvetica", 6, "bold"), fill=fg_col - ) - cv.create_text( - x0 + cw // 2, 16, - text=sym, font=("Helvetica", 7, "bold"), fill=fg_col - ) - return cv - - def _populate_static_hand_examples(self): - for w in self.help_panel.winfo_children(): - w.destroy() - - hdr_row = tk.Frame(self.help_panel, bg=PANEL_BG) - hdr_row.pack(fill="x", pady=(0, 2)) - - tk.Label( - hdr_row, text=t("pk_help_header"), - font=("Georgia", 9, "bold"), fg=ACCENT_GOTH, bg=PANEL_BG - ).pack(side="left") - - InfoBadge( - hdr_row, - text_provider=lambda: t("pk_help_general_info"), - bg=PANEL_BG, - font_size=9, - ).pack(side="right") - - tk.Frame(self.help_panel, bg=SUBTLE_BORDER, height=1).pack(fill="x", pady=(0, 3)) - - cols_wrap = tk.Frame(self.help_panel, bg=PANEL_BG) - cols_wrap.pack(fill="both", expand=True) - cols_wrap.columnconfigure(0, weight=1, uniform="hcol") - cols_wrap.columnconfigure(1, weight=0) - cols_wrap.columnconfigure(2, weight=1, uniform="hcol") - - left_f = tk.Frame(cols_wrap, bg=PANEL_BG) - left_f.grid(row=0, column=0, sticky="nsew", padx=(0, 4)) - - tk.Frame(cols_wrap, bg=SUBTLE_BORDER, width=1).grid(row=0, column=1, sticky="ns", pady=2) - - right_f = tk.Frame(cols_wrap, bg=PANEL_BG) - right_f.grid(row=0, column=2, sticky="nsew", padx=(4, 0)) - - for rank_no, cat_id, cards_spec in HAND_REFERENCE_EXAMPLES: - target_col = left_f if rank_no <= 5 else right_f - cell = tk.Frame(target_col, bg=PANEL_BG) - cell.pack(fill="x", pady=1) - - strip = self._draw_mini_example_strip(cell, cards_spec) - strip.pack(anchor="w") - - lbl_row = tk.Frame(cell, bg=PANEL_BG) - lbl_row.pack(fill="x") - - raw_name = t(f"pk_hand_{cat_id}").replace("★ ", "").replace(" ★", "") - short_name = raw_name.split(" (")[0] - - tk.Label( - lbl_row, - text=f"{rank_no}. {short_name}", - font=("Helvetica", 7, "bold"), - fg=ACCENT_GOLD if rank_no == 1 else FG_COLOR, - bg=PANEL_BG, - anchor="w", - ).pack(side="left") - - InfoBadge( - lbl_row, - text_provider=lambda cid=cat_id: t(f"pk_help_hand_{cid}"), - bg=PANEL_BG, - font_size=8, - ).pack(side="left", padx=(2, 0)) - - # --------------------------------------------------------- - # TISCHBILD SKALIERUNG & HEADER - # --------------------------------------------------------- - def _on_arena_resize(self, event): - w, h = event.width, event.height - if w < 80 or h < 80 or (w, h) == self._last_bg_size: + def _on_arena_configure(self, _event=None): + if not self._canvas_alive(): return - self._last_bg_size = (w, h) + if self._resize_job is not None: + try: + self.ctx.root.after_cancel(self._resize_job) + except Exception: + pass + try: + self._resize_job = self.ctx.root.after(35, self._render_table) + except Exception: + self._resize_job = None - self.arena_canvas.delete("table_bg") - - if self._raw_table_pil is not None: - fitted = self._raw_table_pil.resize((w, h), Image.Resampling.LANCZOS) - self._scaled_table_photo = ImageTk.PhotoImage(fitted) - self.arena_canvas.create_image( - 0, 0, image=self._scaled_table_photo, anchor="nw", tags="table_bg" - ) - self.arena_canvas.tag_lower("table_bg") - else: - mx, my_top, my_bot = int(w * 0.11), int(h * 0.13), int(h * 0.08) - self.arena_canvas.create_oval( - mx, my_top, w - mx, h - my_bot, - fill="#14111b", outline=BORDER_COLOR, width=3, tags="table_bg" - ) + def _get_stretched_table_photo(self, exact_w: int, exact_h: int) -> ImageTk.PhotoImage | None: + if self._raw_table_pil is None or exact_w < 160 or exact_h < 120: + return None + if self._scaled_table_photo is None or self._cached_table_dims != (exact_w, exact_h): + stretched = self._raw_table_pil.resize((exact_w, exact_h), Image.Resampling.LANCZOS) + self._scaled_table_photo = ImageTk.PhotoImage(stretched) + self._cached_table_dims = (exact_w, exact_h) + return self._scaled_table_photo def _refresh_header(self): self.pk_account = Database.get_poker_account(self.pk_account["id"]) - prof = self.ctx.profile - prog = self.ctx.refresh_game_progress() - self.topbar.extra_label.configure(text=t("pk_header_gold", self.pk_account["account_name"], self.pk_account["gold"])) - self.topbar.level_label.configure( - text=t("level_badge", prof["name"], prog["title"], prog["level"], prog["current_xp"], prog["needed_xp"]) - ) + self.topbar.update_level_xp_text() + + gold_str = t("pk_header_gold", self.pk_account["account_name"], self.pk_account["gold"]) street_txt = t(f"pk_street_{self.engine.street}") - self.pot_lbl.configure(text=t("pk_pot_banner", self.engine.total_pot, street_txt, self.engine.current_bet)) + hud_segments = [ + gold_str, + f"~Pot: {self.engine.total_pot}g", + f"~{street_txt}", + ] + if self.devils_locked: + hud_segments.append("~Devil's Gambit") + hud_txt = "|".join(hud_segments) + if hasattr(self, "hud_var") and self.hud_var.get() != hud_txt: + self.hud_var.set(hud_txt) # --------------------------------------------------------- - # HAND STARTEN (Direkter Grundeinsatz / Ante wie bei Blackjack!) + # HAND STARTEN # --------------------------------------------------------- def _start_new_hand(self): if self._result_dialog: self._result_dialog.close_dialog() self._result_dialog = None + ImageButton.close_active_hover_tip() + self._close_hands_overlay() - InfoBadge.close_global_tip() self.pk_account = Database.get_poker_account(self.pk_account["id"]) self.devils_locked = bool(self.pk_account.get("devils_deal_active", 0)) gold = self.pk_account["gold"] @@ -455,8 +512,11 @@ class PokerTableView: cur_cost = self.ctx.refresh_game_progress()["xp_exchange_cost"] msg = t( "bj_err_not_enough_gold_entry", - self.pk_account["account_name"], min_req, gold, - cur_cost, XP_TO_GOLD_AMOUNT + self.pk_account["account_name"], + min_req, + gold, + cur_cost, + XP_TO_GOLD_AMOUNT, ) self._cleanup_and_go(lambda: self.on_back_to_menu(self.pk_account["id"], msg)) return @@ -475,18 +535,21 @@ class PokerTableView: if human_ante > 0: self.pk_account = Database.update_poker_gold(self.pk_account["id"], -human_ante) - ante_lbl = "Grundeinsatz" if get_lang() == "DE" else "Entry Ante" for s_idx, (_b_role, b_amt) in ante_events.items(): if s_idx > 0: - self.engine.seats[s_idx].status_text = f"{ante_lbl} ({b_amt}g)" + self.engine.seats[s_idx].status_text = t("pk_ante_status", b_amt) self._persist_state() - self._build_ui() + if not self._canvas_alive(): + self._build_ui() + else: + self.topbar.set_locked_exit(self.devils_locked) + self._render_table() self._process_current_turn() # --------------------------------------------------------- - # RENDERING TISCH + # VOLL-CANVAS RENDERING (6-MAX BOTS, BOARD & POT INNEN, SPIELER + REFERENZ UNTEN) # --------------------------------------------------------- def _role_badge(self, seat_idx: int) -> str: badges = [] @@ -498,106 +561,324 @@ class PokerTableView: badges.append(t("pk_role_bb")) return "".join(badges) - def _render_table(self): - self._photo_refs.clear() - - for old_f in self._bot_seat_frames: - if old_f.winfo_exists(): - old_f.destroy() - self._bot_seat_frames.clear() - + def _draw_bots_around_table( + self, + cw: int, + ch: int, + pad_x: int, + pad_top: int, + pad_bot: int, + table_rect: tuple[int, int, int, int], + ) -> int: bot_seats = self.engine.seats[1:] + if not bot_seats: + return table_rect[1] + 24 + + tx1, ty1, tx2, ty2 = table_rect + box_h = 88 + base_box_w = 204 + + top_cy = max(pad_top + box_h // 2, ty1 + box_h // 2 - 4) + bot_cy = min(ch - pad_bot - box_h // 2, ty2 - box_h // 2 + 22) + if bot_cy - top_cy < box_h + 16: + mid_y = (top_cy + bot_cy) // 2 + top_cy = mid_y - (box_h + 16) // 2 + bot_cy = mid_y + (box_h + 16) // 2 + + top_center_cy = max(pad_top + box_h // 2, ty1 + int(box_h * 0.42)) + top_center_bottom = ty1 + 24 + slot_indices = SEAT_LAYOUT_BY_COUNT.get(len(bot_seats), (0, 1, 2, 3, 4)) + name_sz = max(14, FONT_SIZE_BODY - 1) + sub_sz = max(13, FONT_SIZE_BODY - 2) for bot_i, seat in enumerate(bot_seats): coord_idx = slot_indices[bot_i] - rx, ry = OVAL_BOT_COORDS[coord_idx] - is_turn = (self.engine.street != "SHOWDOWN" and self.engine.turn_pos == seat.seat_id) - if is_turn: - b_col, thick = ACCENT_GOLD, 2 - elif seat.folded: - b_col, thick = ERROR_FG, 1 - elif seat.all_in: - b_col, thick = ACCENT_GOTH, 2 - else: - b_col, thick = BORDER_COLOR, 1 - box = tk.Frame( - self.arena_canvas, bg="#191521", padx=10, pady=5, width=188, - highlightthickness=thick, highlightbackground=b_col - ) - box.place(relx=rx, rely=ry, anchor="center") - self._bot_seat_frames.append(box) + frame_style = "gold" if is_turn else "purple" + if seat.folded: + status_border = ERROR_FG + elif seat.all_in: + status_border = ACCENT_GOTH + else: + status_border = None base_name = t("bj_bot_rebuy", seat.name) if seat.rebought else seat.name title_txt = f"{base_name}{self._role_badge(seat.seat_id)}" - tk.Label( - box, text=title_txt, font=("Georgia", 9, "bold"), - fg=MUTED_FG if seat.folded else ACCENT_GOTH, bg="#191521" - ).pack() - - tk.Label( - box, text=t("pk_bot_stack_lbl", seat.stack, seat.street_bet), - font=("Helvetica", 8, "bold"), fg=ACCENT_GOLD, bg="#191521" - ).pack(pady=(1, 2)) + title_col = MUTED_FG if seat.folded else (ACCENT_GOLD if is_turn else ACCENT_GOTH) + stack_txt = t("pk_bot_stack_lbl", seat.stack, seat.street_bet) st_txt = seat.status_text or "—" st_col = ERROR_FG if seat.folded else (ACCENT_GOLD if is_turn else FG_COLOR) - tk.Label(box, text=st_txt, font=("Helvetica", 8, "bold"), fg=st_col, bg="#191521").pack() - # 2. Gemeinschaftskarten (Board) - felt_bg = "#1b1626" - for w in self.board_cards_frame.winfo_children(): - w.destroy() + title_ph = self._make_goth_photo(title_txt, size_px=name_sz, color=title_col, max_width=230) + stack_ph = self._make_goth_photo(stack_txt, size_px=sub_sz, color=ACCENT_GOLD, max_width=230) + st_ph = self._make_goth_photo(st_txt, size_px=sub_sz, color=st_col, max_width=230) + + widest_txt = max( + (ph.width() for ph in (title_ph, stack_ph, st_ph) if ph is not None), + default=148, + ) + box_w = max(base_box_w, min(274, widest_txt + 52)) + + if coord_idx == 2: + bx, by = cw // 2, top_center_cy + top_center_bottom = max(top_center_bottom, by + box_h // 2) + elif coord_idx in (0, 1): + bx = max(pad_x + box_w // 2, tx1 + int(box_w * 0.36)) + by = bot_cy if coord_idx == 0 else top_cy + else: + bx = min(cw - pad_x - box_w // 2, tx2 - int(box_w * 0.36)) + by = top_cy if coord_idx == 3 else bot_cy + + self._draw_framed_panel( + bx, by, box_w, box_h, frame_style=frame_style, status_border=status_border + ) + + self._place_goth_photo_or_fallback(bx, by - 23, title_ph, title_txt, name_sz, title_col) + self._place_goth_photo_or_fallback(bx, by, stack_ph, stack_txt, sub_sz, ACCENT_GOLD) + self._place_goth_photo_or_fallback(bx, by + 23, st_ph, st_txt, sub_sz, st_col) + + return top_center_bottom + + def _draw_board_and_pot_inside_table( + self, + table_rect: tuple[int, int, int, int], + top_obstacle_y: int, + player_top_y: int, + ): + tx1, ty1, tx2, ty2 = table_rect + t_cx = (tx1 + tx2) // 2 + t_h = max(260, ty2 - ty1) + + felt_top = max(ty1 + max(32, int(t_h * 0.14)), top_obstacle_y + 12) + felt_bot = min(ty2 - max(24, int(t_h * 0.10)), player_top_y - 10) + avail_h = max(148, felt_bot - felt_top) + + base_cw, base_ch = PK_OVAL_BOARD_CARD + max_board_ch = max(84, min(base_ch, avail_h - 58)) + scale = max_board_ch / max(1, base_ch) + card_w = max(58, int(round(base_cw * scale))) + card_h = int(round(base_ch * scale)) + card_sz = (card_w, card_h) + + gap = max(8, int(card_w * 0.13)) + total_board_w = 5 * card_w + 4 * gap + start_x = t_cx - total_board_w // 2 + board_cy = felt_top + card_h // 2 + max(4, (avail_h - card_h - 52) // 3) + card_top = board_cy - card_h // 2 for slot_i in range(5): + sx = start_x + slot_i * (card_w + gap) if slot_i < len(self.engine.board): c = self.engine.board[slot_i] - photo = self.ctx.assets.get_card_photo(c.image_filename, size=PK_OVAL_BOARD_CARD) + photo = self.ctx.assets.get_card_photo(c.image_filename, size=card_sz) if photo: self._photo_refs.append(photo) - tk.Label(self.board_cards_frame, image=photo, bg=felt_bg, bd=0).pack(side="left", padx=5) - else: - empty_slot = tk.Frame( - self.board_cards_frame, width=PK_OVAL_BOARD_CARD[0], height=PK_OVAL_BOARD_CARD[1], - bg="#221c2e", highlightthickness=1, highlightbackground=SUBTLE_BORDER - ) - empty_slot.pack(side="left", padx=5) + self.arena_canvas.create_image( + sx, card_top, image=photo, anchor="nw", tags="fg" + ) + continue - # 3. Eigene Karten + neutrale Einsatz-Info - for w in self.player_sec.winfo_children(): - w.destroy() + self.arena_canvas.create_rectangle( + sx, + card_top, + sx + card_w, + card_top + card_h, + fill="#161220", + outline=SUBTLE_BORDER, + width=1, + tags="fg", + ) + self.arena_canvas.create_text( + sx + card_w // 2, + card_top + card_h // 2, + text="♦", + font=("Georgia", max(12, card_w // 5)), + fill="#2d243b", + tags="fg", + ) + pot_raw = t("pk_pot_banner", self.engine.total_pot, "", self.engine.current_bet) + pot_txt = pot_raw.split("|")[0].strip() + + pot_cy = min( + felt_bot - 20, + max(board_cy + card_h // 2 + 28, (board_cy + card_h // 2 + felt_bot) // 2), + ) + pot_sz = max(15, FONT_SIZE_BODY) + pot_ph = self._make_goth_photo(pot_txt, size_px=pot_sz, color=FONT_COLOR_TITLE_MAIN) + if pot_ph is not None: + bw = max(230, pot_ph.width() + 64) + bh = max(38, pot_ph.height() + 16) + self._draw_framed_panel(t_cx, pot_cy, bw, bh, frame_style="gold") + self.arena_canvas.create_image(t_cx, pot_cy, image=pot_ph, anchor="center", tags="fg") + else: + self._draw_framed_panel(t_cx, pot_cy, 240, 38, frame_style="gold") + self._place_goth_photo_or_fallback( + t_cx, pot_cy, None, pot_txt, size_px=pot_sz, color=ACCENT_GOLD + ) + + def _draw_human_hand_below_table( + self, cw: int, pad_x: int, player_zone_top: int, player_zone_bot: int + ): human = self.engine.human_seat - h_cards_f = tk.Frame(self.player_sec, bg=PANEL_BG) - h_cards_f.pack(expand=True, pady=(2, 2)) + avail_h = max(140, player_zone_bot - player_zone_top) + zone_cy = (player_zone_top + player_zone_bot) // 2 + base_w, base_h = PLAYING_CARD_SIZE + max_card_h = max(88, min(base_h, avail_h - 52)) + scale = max_card_h / max(1, base_h) + card_w = max(60, int(round(base_w * scale))) + card_h = int(round(base_h * scale)) + card_sz = (card_w, card_h) + + p_photos = [] for card in human.hole_cards: - photo = self.ctx.assets.get_card_photo(card.image_filename, size=PLAYING_CARD_SIZE) + photo = self.ctx.assets.get_card_photo(card.image_filename, size=card_sz) if photo: self._photo_refs.append(photo) - tk.Label(h_cards_f, image=photo, bg=PANEL_BG, bd=0).pack(side="left", padx=6) + p_photos.append(photo) - state_tag = t("pk_state_folded") if human.folded else (t("pk_state_allin") if human.all_in else "") + state_tag = ( + t("pk_state_folded") + if human.folded + else (t("pk_state_allin") if human.all_in else "") + ) role_str = self._role_badge(0) or t("pk_role_player") - tk.Label( - self.player_sec, - text=t("pk_player_bet_only", role_str, human.street_bet, human.total_committed, state_tag), - font=("Georgia", 10, "bold"), - fg=ERROR_FG if human.folded else FG_COLOR, - bg=PANEL_BG, - wraplength=410, - justify="center", - ).pack(side="bottom", pady=(2, 2)) + lbl_txt = t( + "pk_player_bet_only", + role_str, + human.street_bet, + human.total_committed, + state_tag, + ) + is_my_turn = ( + self.engine.street != "SHOWDOWN" + and self.engine.turn_pos == 0 + and human.can_act + ) + lbl_col = ERROR_FG if human.folded else FONT_COLOR_TITLE_MAIN + lbl_sz = max(14, FONT_SIZE_BODY - 1) + lbl_ph = self._make_goth_photo(lbl_txt, size_px=lbl_sz, color=lbl_col) + + cards_gap = 12 + cards_span_w = ( + len(p_photos) * card_w + max(0, len(p_photos) - 1) * cards_gap + if p_photos + else card_w * 2 + ) + txt_w = lbl_ph.width() if lbl_ph is not None else 250 + + box_w = max(300, min(540, max(cards_span_w + 96, txt_w + 72))) + box_h = min(avail_h, card_h + 52) + box_cx = cw // 2 + + status_bdr = ERROR_FG if human.folded else (ACCENT_GOTH if human.all_in else None) + self._draw_framed_panel( + box_cx, + zone_cy, + box_w, + box_h, + frame_style="gold" if is_my_turn else "purple", + status_border=status_bdr, + ) + + if p_photos: + c_start_x = box_cx - cards_span_w // 2 + c_top_y = (zone_cy - 11) - card_h // 2 + for idx, ph in enumerate(p_photos): + self.arena_canvas.create_image( + c_start_x + idx * (card_w + cards_gap), + c_top_y, + image=ph, + anchor="nw", + tags="fg", + ) + + self._place_goth_photo_or_fallback( + box_cx, zone_cy + box_h // 2 - 20, lbl_ph, lbl_txt, lbl_sz, lbl_col + ) + + if self._card_ref_btn is not None and self._card_ref_btn.winfo_exists(): + if self._result_dialog is not None: + self._card_ref_btn.place_forget() + else: + ref_bw = self._card_ref_btn.pixel_width + ref_bh = self._card_ref_btn.pixel_height + ref_x = box_cx + box_w // 2 + 16 + if ref_x + ref_bw > cw - pad_x - 6: + ref_x = max(pad_x + 6, box_cx - box_w // 2 - ref_bw - 16) + ref_y = zone_cy + box_h // 2 - ref_bh - 6 + self._card_ref_btn.place(x=ref_x, y=ref_y, width=ref_bw, height=ref_bh) + tk.Widget.tkraise(self._card_ref_btn) + + def _render_table(self): + if not self._canvas_alive(): + return + + cw = max(760, self.arena_canvas.winfo_width()) + ch = max(460, self.arena_canvas.winfo_height()) + + bg_ids = set(self.arena_canvas.find_withtag("table_bg_slice")) + for item_id in self.arena_canvas.find_all(): + if item_id not in bg_ids: + self.arena_canvas.delete(item_id) + self._photo_refs.clear() + + self._bg_renderer.draw_on_canvas(self.arena_canvas, cw, ch) + + pad_x = max(24, int(cw * 0.022)) + pad_top = 6 + pad_bot = 6 + + player_zone_h = max(150, min(174, int(ch * 0.31))) + player_zone_bot = ch - pad_bot + player_zone_top = player_zone_bot - player_zone_h + + table_top = pad_top + table_bot = min(ch - pad_bot - 60, player_zone_top + 64) + table_h = max(280, table_bot - table_top) + table_w = max(680, cw - 2 * pad_x - 90) + table_cx = cw // 2 + table_cy = table_top + table_h // 2 + table_rect = ( + table_cx - table_w // 2, + table_top, + table_cx + table_w // 2, + table_top + table_h, + ) + + tbl_photo = self._get_stretched_table_photo(table_w, table_h) + if tbl_photo is not None: + self.arena_canvas.create_image( + table_cx, table_cy, image=tbl_photo, anchor="center", tags="fg" + ) + else: + self.arena_canvas.create_oval( + table_rect[0], table_rect[1], table_rect[2], table_rect[3], + fill="#14111b", outline=BORDER_COLOR, width=3, tags="fg", + ) + + top_obstacle_y = self._draw_bots_around_table( + cw, ch, pad_x, pad_top, pad_bot, table_rect + ) + self._draw_board_and_pot_inside_table(table_rect, top_obstacle_y, player_zone_top) + self._draw_human_hand_below_table(cw, pad_x, player_zone_top, player_zone_bot) self._refresh_header() + if self._hands_overlay is not None and self._hands_overlay.winfo_exists(): + tk.Widget.tkraise(self._hands_overlay) + if self._result_dialog is not None and self._result_dialog.winfo_exists(): + tk.Widget.tkraise(self._result_dialog) + # --------------------------------------------------------- - # ZUG-SCHLEIFE & STRASSEN-WECHSEL + # ZUG-SCHLEIFE & BOTTOM-BAR AKTIONEN MIT HOVER-HILFE # --------------------------------------------------------- def _process_current_turn(self): - if not self.table_frame.winfo_exists(): + if not self._canvas_alive(): return if self.engine.only_one_left(): @@ -620,9 +901,10 @@ class PokerTableView: else: self._render_waiting_controls() bot = self.engine.seats[self.engine.turn_pos] - self.status_lbl.configure(text=t("pk_bot_turn_status", bot.name)) self._render_table() - self._turn_job = self.ctx.root.after(PK_BOT_TURN_DELAY_MS, lambda b=bot: self._execute_bot_turn(b)) + self._turn_job = self.ctx.root.after( + PK_BOT_TURN_DELAY_MS, lambda b=bot: self._execute_bot_turn(b) + ) def _advance_street_or_showdown(self): self._render_waiting_controls() @@ -641,152 +923,122 @@ class PokerTableView: return if self.engine.should_auto_runout_board(): - self.status_lbl.configure(text=t("pk_showdown_running")) - self._turn_job = self.ctx.root.after(PK_STREET_DELAY_MS, self._advance_street_or_showdown) + self._turn_job = self.ctx.root.after( + PK_STREET_DELAY_MS, self._advance_street_or_showdown + ) else: self._process_current_turn() - # --------------------------------------------------------- - # RECHTE SPALTE: VERTIKALE BUTTONS + ⓘ INFO-SYMBOLE (U+24D8) - # --------------------------------------------------------- - def _add_action_row( - self, - parent: tk.Frame, - text: str, - pil_norm, - pil_hov, - command, - tip_key: str, - sound_mgr=None, - enabled: bool = True, - btn_w: int = 176, - btn_h: int = 29, - pady: tuple[int, int] = (1, 2), - ): - row = tk.Frame(parent, bg=PANEL_BG) - row.pack(pady=pady) - - ImageButton( - row, - text, - pil_norm, - pil_hov, - command, - sound_mgr=sound_mgr, - width=btn_w, - height=btn_h, - font=("Helvetica", 9, "bold"), - enabled=enabled, - ).pack(side="left") - - InfoBadge( - row, - text_provider=lambda k=tip_key: t(k), - bg=PANEL_BG, - font_size=9, - ).pack(side="left", padx=(5, 0)) - def _render_waiting_controls(self): - for w in self.controls_frame.winfo_children(): - w.destroy() - - col = tk.Frame(self.controls_frame, bg=PANEL_BG) - col.pack(expand=True) - - self._add_action_row( - col, t("pk_btn_check"), - self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active, - None, "pk_tip_check", enabled=False, pady=(3, 3) - ) - self._add_action_row( - col, t("pk_btn_allin", 0), - self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active, - None, "pk_tip_allin", enabled=False, pady=(3, 3) - ) - self._add_action_row( - col, t("pk_btn_fold"), - self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active, - None, "pk_tip_fold", enabled=False, pady=(3, 3) - ) + if not hasattr(self, "bottom_bar") or not self.bottom_bar.winfo_exists(): + return + self._set_bottom_buttons([]) def _show_human_controls(self): - for w in self.controls_frame.winfo_children(): - w.destroy() + if not hasattr(self, "bottom_bar") or not self.bottom_bar.winfo_exists(): + return human = self.engine.human_seat to_call = max(0, self.engine.current_bet - human.street_bet) - street_txt = t(f"pk_street_{self.engine.street}") dyn_chips = self._get_current_level_chips() - if to_call > 0: - self.status_lbl.configure(text=t("pk_turn_prompt_call", street_txt, min(human.stack, to_call))) - else: - self.status_lbl.configure(text=t("pk_turn_prompt_check", street_txt)) + btn_norm = self.ctx.assets.raw_btn_default + btn_purp = self.ctx.assets.raw_btn_purple + btn_fire = self.ctx.assets.raw_btn_fire or btn_purp - btn_col = tk.Frame(self.controls_frame, bg=PANEL_BG) - btn_col.pack(expand=True) + primary_btns: list[ImageButton] = [] + overflow_btns: list[ImageButton] = [] - # 1. Check (Hold) oder Mitgehen (Call) + ⓘ if to_call == 0: - self._add_action_row( - btn_col, t("pk_btn_check"), - self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active, - lambda: self._on_human_action("CHECK", 0), - "pk_tip_check", sound_mgr=None, btn_h=29, pady=(0, 2) + primary_btns.append( + ImageButton( + self.bottom_bar, + t("pk_btn_check"), + btn_fire, + btn_fire, + lambda: self._on_human_action("CHECK", 0), + sound_mgr=None, + width=138, + height=30, + style="fire", + hover_text=lambda: t("pk_tip_check"), + ) ) elif human.stack > to_call: - self._add_action_row( - btn_col, t("pk_btn_call", to_call), - self.ctx.assets.raw_btn, self.ctx.assets.raw_btn_active, - lambda: self._on_human_action("CALL", 0), - "pk_tip_call", sound_mgr=self.ctx.sounds, btn_h=29, pady=(0, 2) + primary_btns.append( + ImageButton( + self.bottom_bar, + t("pk_btn_call", to_call), + btn_fire, + btn_fire, + lambda: self._on_human_action("CALL", 0), + sound_mgr=self.ctx.sounds, + width=138, + height=30, + style="fire", + hover_text=lambda: t("pk_tip_call"), + ) ) - # 2. Erhöhen (Raise) Header + ⓘ & kompakter 2x2 Chip-Block avail_after_call = human.stack - to_call min_r = self.engine.min_raise_delta offered = sorted({max(min_r, c) for c in dyn_chips if max(min_r, c) < avail_after_call})[:4] - if avail_after_call > min_r and offered: - r_hdr = tk.Frame(btn_col, bg=PANEL_BG) - r_hdr.pack(pady=(1, 1)) - tk.Label( - r_hdr, text=t("pk_raise_lbl"), - font=("Helvetica", 8, "bold"), fg=MUTED_FG, bg=PANEL_BG - ).pack(side="left") - InfoBadge( - r_hdr, text_provider=lambda: t("pk_tip_raise"), bg=PANEL_BG, font_size=9 - ).pack(side="left", padx=(4, 0)) - - r_grid = tk.Frame(btn_col, bg=PANEL_BG) - r_grid.pack(pady=(0, 2)) - for idx, r_delta in enumerate(offered): + for r_delta in offered: + primary_btns.append( ImageButton( - r_grid, f"+{r_delta}", - self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active, + self.bottom_bar, + f"+{r_delta}g", + btn_norm, + btn_purp, lambda d=r_delta: self._on_human_action("RAISE", d), - sound_mgr=self.ctx.sounds, width=85, height=25, font=("Helvetica", 8, "bold") - ).grid(row=idx // 2, column=idx % 2, padx=2, pady=1) - - # 3. ALL-IN + ⓘ - if human.stack > 0: - self._add_action_row( - btn_col, t("pk_btn_allin", human.stack), - self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active, - lambda: self._on_human_action("ALLIN", 0), - "pk_tip_allin", sound_mgr=self.ctx.sounds, btn_h=28, pady=(1, 2) + sound_mgr=self.ctx.sounds, + width=74, + height=30, + style="amethyst", + hover_text=lambda: t("pk_tip_raise"), + ) ) - # 4. Passen (Fold) + ⓘ - self._add_action_row( - btn_col, t("pk_btn_fold"), - self.ctx.assets.raw_sel, self.ctx.assets.raw_sel_active, - lambda: self._on_human_action("FOLD", 0), - "pk_tip_fold", sound_mgr=self.ctx.sounds, btn_h=28, pady=(0, 0) + if human.stack > 0: + allin_style = "fire" if (to_call > 0 and human.stack <= to_call) else "amethyst" + allin_bg = btn_fire if allin_style == "fire" else btn_norm + allin_hov = btn_fire if allin_style == "fire" else btn_purp + overflow_btns.append( + ImageButton( + self.bottom_bar, + t("pk_btn_allin", human.stack), + allin_bg, + allin_hov, + lambda: self._on_human_action("ALLIN", 0), + sound_mgr=self.ctx.sounds, + width=132, + height=30, + style=allin_style, + hover_text=lambda: t("pk_tip_allin"), + ) + ) + + overflow_btns.append( + ImageButton( + self.bottom_bar, + t("pk_btn_fold"), + btn_norm, + btn_purp, + lambda: self._on_human_action("FOLD", 0), + sound_mgr=self.ctx.sounds, + width=122, + height=30, + style="amethyst", + hover_text=lambda: t("pk_tip_fold"), + ) ) + self._set_bottom_buttons(primary_btns, overflow_buttons=overflow_btns) + def _on_human_action(self, action: str, raise_delta: int): - InfoBadge.close_global_tip() + ImageButton.close_active_hover_tip() + self._close_hands_overlay() if action == "CHECK": self.ctx.sounds.play("stand") paid = self.engine.apply_action(0, action, raise_delta) @@ -802,10 +1054,12 @@ class PokerTableView: # BOT-ZUG AUSFÜHREN # --------------------------------------------------------- def _execute_bot_turn(self, bot: PokerSeat): - if not self.table_frame.winfo_exists(): + if not self._canvas_alive(): return - active_opps = sum(1 for s in self.engine.seats if s.is_in_hand and s.seat_id != bot.seat_id) + active_opps = sum( + 1 for s in self.engine.seats if s.is_in_hand and s.seat_id != bot.seat_id + ) dyn_chips = self._get_current_level_chips() act, r_delta = self.bot_ai.decide_action( @@ -858,12 +1112,15 @@ class PokerTableView: return entries def _finalize_hand(self): - InfoBadge.close_global_tip() - self._render_waiting_controls() + ImageButton.close_active_hover_tip() + self._close_hands_overlay() + self._set_bottom_buttons([]) res = self.engine.resolve_hand() if res["human_payout"] > 0: - self.pk_account = Database.update_poker_gold(self.pk_account["id"], res["human_payout"]) + self.pk_account = Database.update_poker_gold( + self.pk_account["id"], res["human_payout"] + ) duration = max(0.5, time.time() - self.round_start_time) prog_before = self.ctx.refresh_game_progress() @@ -891,11 +1148,18 @@ class PokerTableView: Database.add_game_points(self.ctx.profile["id"], GAME_FOLDER_ID, xp_gained) prog_after = self.ctx.refresh_game_progress() self.ctx.sounds.play("end_battle") - leveled_to = prog_after["level"] if prog_after["level"] > prog_before["level"] else None + leveled_to = ( + prog_after["level"] + if prog_after["level"] > prog_before["level"] + else None + ) else: old_lvl, new_lvl = self.ctx.record_result( - self.variant_key, won=won_stat, duration_sec=duration, - points_gained=xp_gained, pk_account_id=self.pk_account["id"] + self.variant_key, + won=won_stat, + duration_sec=duration, + points_gained=xp_gained, + pk_account_id=self.pk_account["id"], ) leveled_to = new_lvl if new_lvl > old_lvl else None @@ -924,10 +1188,9 @@ class PokerTableView: self._last_popup_payload = payload if self.devils_locked: self._persist_state() - else: - self._build_ui() + elif self._canvas_alive(): + self.topbar.set_locked_exit(False) - self.status_lbl.configure(text="") self._render_table() self._open_result_popup(self._build_localized_popup_data(payload)) @@ -939,19 +1202,27 @@ class PokerTableView: hand_desc = t(f"pk_hand_{cat}") if payload["player_won"]: - headline = t("pk_popup_split_won", hand_desc) if payload["is_split"] else t("pk_popup_player_won", hand_desc) + headline = ( + t("pk_popup_split_won", hand_desc) + if payload["is_split"] + else t("pk_popup_player_won", hand_desc) + ) else: - headline = t("pk_popup_bot_won", ", ".join(payload["winner_names"]), hand_desc) + headline = t( + "pk_popup_bot_won", ", ".join(payload["winner_names"]), hand_desc + ) other_gains = [ t("pk_popup_bot_gain", b_name, b_gain) - for b_name, b_gain in payload["bot_gains"] if b_gain > 0 + for b_name, b_gain in payload["bot_gains"] + if b_gain > 0 ] lvl_to = payload["leveled_to"] lvl_str = ( t("bj_popup_level_up", lvl_to, Progression.get_prestige_title(lvl_to)) - if lvl_to is not None else None + if lvl_to is not None + else None ) seat_showdown = [] @@ -987,11 +1258,16 @@ class PokerTableView: } def _open_result_popup(self, popup_data: dict): + self._set_bottom_buttons([]) + if self._card_ref_btn is not None and self._card_ref_btn.winfo_exists(): + self._card_ref_btn.place_forget() self._result_dialog = PokerResultDialog( - parent=self.table_frame, + parent=self.arena_canvas, assets=self.ctx.assets, sounds=self.ctx.sounds, result_data=popup_data, on_next_round=self._start_new_hand, - on_back_to_menu=lambda: self._cleanup_and_go(lambda: self.on_back_to_menu(self.pk_account["id"])), + on_back_to_menu=lambda: self._cleanup_and_go( + lambda: self.on_back_to_menu(self.pk_account["id"]) + ), ) \ No newline at end of file diff --git a/games/solitaire/base/__pycache__/solitaire_core.cpython-311.pyc b/games/solitaire/base/__pycache__/solitaire_core.cpython-311.pyc index dba0076..9512b5b 100644 Binary files a/games/solitaire/base/__pycache__/solitaire_core.cpython-311.pyc and b/games/solitaire/base/__pycache__/solitaire_core.cpython-311.pyc differ diff --git a/games/solitaire/base/__pycache__/solitaire_theme.cpython-311.pyc b/games/solitaire/base/__pycache__/solitaire_theme.cpython-311.pyc index 37de268..579767b 100644 Binary files a/games/solitaire/base/__pycache__/solitaire_theme.cpython-311.pyc and b/games/solitaire/base/__pycache__/solitaire_theme.cpython-311.pyc differ diff --git a/games/solitaire/base/solitaire_bottom_bar.py b/games/solitaire/base/solitaire_bottom_bar.py index c063d46..6ea768d 100644 --- a/games/solitaire/base/solitaire_bottom_bar.py +++ b/games/solitaire/base/solitaire_bottom_bar.py @@ -20,16 +20,24 @@ BG_SAFE_BOTTOM_RATIO = getattr(gc, "BG_SAFE_BOTTOM_RATIO", 0.095) class SolitaireBottomBar(tk.Canvas): """ - Gerahmte HUD- & Aktionsleiste innerhalb der unteren Safe-Area von background.jpg: - Sitzt oberhalb des unteren Dornenrahmens, lässt die Spinnweben frei und hält - den sekündlichen Timer aus dem globalen Text-Cache fern. + Gerahmte HUD- & Aktionsleiste innerhalb der unteren Safe-Area von background.jpg. + Unterstützt kompakte Pipe-Trenner ('|') sowie zwei optionale Overflow-Erweiterungsflächen + links (für Text-Segmente mit Präfix '~') und rechts (für sekundäre Aktions-Buttons), + die automatisch nur dann eingeblendet werden, wenn der Platz in der Hauptleiste eng wird. """ CONTENT_H = 48 + SUB_TOP_GAP = 3 + SUB_BAR_H = 38 + MIN_BOTTOM_INSET = 56 + + # Fein-Offsets für den linken HUD-Textblock ("Punkte: 0 | Züge: 0 | ...") + HUD_TEXT_X_OFFSET = 0 # Positiv = weiter nach rechts zur Mitte, Negativ = näher an den linken Rahmen + HUD_TEXT_Y_OFFSET = 6 # Optische Vertikalzentrierung im Goldrahmen def __init__(self, parent, ctx, hud_var: tk.StringVar, status_var: tk.StringVar): root_h = max(720, ctx.root.winfo_height()) - self._bottom_inset = max(54, int(root_h * BG_SAFE_BOTTOM_RATIO)) + self._bottom_inset = max(self.MIN_BOTTOM_INSET, int(root_h * BG_SAFE_BOTTOM_RATIO)) init_h = self.CONTENT_H + self._bottom_inset super().__init__( @@ -47,15 +55,45 @@ class SolitaireBottomBar(tk.Canvas): self._buttons: list[ImageButton] = [] self._bg_ph: ImageTk.PhotoImage | None = None self._frame_ph: ImageTk.PhotoImage | None = None + self._sub_left_frame_ph: ImageTk.PhotoImage | None = None + self._sub_right_frame_ph: ImageTk.PhotoImage | None = None self._txt_refs: list[ImageTk.PhotoImage] = [] - self._btn_left_limit: int = 500 + self._last_btn_split: tuple[tuple[int, ...], tuple[int, ...]] | None = None self.hud_var.trace_add("write", lambda *_: self.refresh_texts()) self.status_var.trace_add("write", lambda *_: self.refresh_texts()) self.bind("", self._on_configure) - def set_buttons(self, buttons: list[ImageButton]): - self._buttons = list(buttons) + def set_buttons( + self, + buttons: list[ImageButton], + overflow_buttons: list[ImageButton] | None = None, + ): + """ + Setzt die aktiven Leisten-Buttons und räumt alte Button-Widgets sauber ab. + Buttons in `overflow_buttons` (oder mit Attribut `can_overflow=True`) bleiben + solange möglich oben in der Hauptleiste und weichen bei Platzmangel automatisch + rechtsbündig in die untere rechte Erweiterungsfläche aus. + """ + primary_list = list(buttons) + extra_list = list(overflow_buttons) if overflow_buttons else [] + for b in extra_list: + setattr(b, "can_overflow", True) + + combined = primary_list + extra_list + keep_ids = {id(b) for b in combined} + + for old_b in self._buttons: + if id(old_b) not in keep_ids: + try: + if old_b.winfo_exists(): + old_b.place_forget() + old_b.destroy() + except Exception: + pass + + self._buttons = combined + self._last_btn_split = None self.relayout() self.after(20, self.relayout) @@ -102,7 +140,7 @@ class SolitaireBottomBar(tk.Canvas): return root_h = max(600, self.ctx.root.winfo_height()) - new_bot = max(52, int(root_h * BG_SAFE_BOTTOM_RATIO)) + new_bot = max(self.MIN_BOTTOM_INSET, int(root_h * BG_SAFE_BOTTOM_RATIO)) if new_bot != self._bottom_inset: self._bottom_inset = new_bot h = self.CONTENT_H + self._bottom_inset @@ -111,80 +149,320 @@ class SolitaireBottomBar(tk.Canvas): self._slice_bg(w, h) self._layout(w, h) + def _render_seg_photo(self, txt: str) -> ImageTk.PhotoImage: + # Dynamische Timer-Segmente (z. B. 00:12) nicht dauerhaft im Text-Cache ablegen + if ":" in txt and any(ch.isdigit() for ch in txt) and "'" not in txt: + try: + pil_seg = self.assets.render_goth_text_pil( + txt, + size_px=FONT_SIZE_SMALL_MIN + 1, + color=FONT_COLOR_HEADING_SUB, + align="left", + uncached=True, + ) + except TypeError: + pil_seg = self.assets.render_goth_text_pil( + txt, + size_px=FONT_SIZE_SMALL_MIN + 1, + color=FONT_COLOR_HEADING_SUB, + align="left", + ) + return ImageTk.PhotoImage(pil_seg) + + return self.assets.get_goth_text_photo( + txt, + size_px=FONT_SIZE_SMALL_MIN + 1, + color=FONT_COLOR_HEADING_SUB, + align="left", + ) + + def _prepare_hud_segments(self) -> tuple[list[dict], ImageTk.PhotoImage, int]: + raw_hud = (self.hud_var.get() or "").replace("•", "|") + raw_parts = [p.strip() for p in raw_hud.split("|") if p.strip()] + + pipe_ph = self.assets.get_goth_text_photo( + "|", + size_px=FONT_SIZE_SMALL_MIN + 1, + color=FONT_COLOR_HEADING_SUB, + align="center", + ) + pipe_step = pipe_ph.width() + 12 + + items: list[dict] = [] + for part in raw_parts: + can_ovf = part.startswith("~") + clean_txt = part[1:].strip() if can_ovf else part + if not clean_txt: + continue + ph = self._render_seg_photo(clean_txt) + items.append({ + "text": clean_txt, + "photo": ph, + "w": ph.width(), + "can_overflow": can_ovf, + }) + return items, pipe_ph, pipe_step + + @staticmethod + def _calc_segs_width(segs: list[dict], pipe_step: int) -> int: + if not segs: + return 0 + return sum(s["w"] for s in segs) + max(0, len(segs) - 1) * pipe_step + + @staticmethod + def _calc_btns_width(btns: list[ImageButton]) -> int: + if not btns: + return 0 + return sum(b.pixel_width for b in btns) + max(0, len(btns) - 1) * 6 + + def _compute_partition( + self, w: int + ) -> tuple[list[dict], list[dict], list[ImageButton], list[ImageButton], ImageTk.PhotoImage, int]: + seg_items, pipe_ph, pipe_step = self._prepare_hud_segments() + + side_inset = max(92, int(w * BG_SAFE_SIDE_RATIO)) + avail_main_w = max(200, (w - 2 * side_inset) - 32) + min_mid_gap = 22 + + avail_left_wing = max(120, int(w * 0.415) - side_inset - 24) + avail_right_wing = max(120, (w - side_inset) - int(w * 0.585) - 24) + + top_segs = list(seg_items) + sub_segs: list[dict] = [] + + alive_btns = [b for b in self._buttons if b.winfo_exists()] + top_btns = list(alive_btns) + sub_btns: list[ImageButton] = [] + + def fits_main() -> bool: + sw = self._calc_segs_width(top_segs, pipe_step) + bw = self._calc_btns_width(top_btns) + if sw > 0 and bw > 0: + return (sw + min_mid_gap + bw) <= avail_main_w + return (sw + bw) <= avail_main_w + + guard = 0 + while not fits_main() and guard < 24: + guard += 1 + moved = False + + for idx in range(len(top_btns) - 1, -1, -1): + cand = top_btns[idx] + if getattr(cand, "can_overflow", False): + test_sub = [cand] + sub_btns + if self._calc_btns_width(test_sub) <= avail_right_wing or not sub_btns: + sub_btns.insert(0, top_btns.pop(idx)) + moved = True + break + if moved: + continue + + for idx in range(len(top_segs) - 1, 0, -1): + cand_s = top_segs[idx] + if cand_s["can_overflow"]: + test_sub_s = [cand_s] + sub_segs + if self._calc_segs_width(test_sub_s, pipe_step) <= avail_left_wing or not sub_segs: + sub_segs.insert(0, top_segs.pop(idx)) + moved = True + break + if moved: + continue + + if len(top_btns) > 1: + cand = top_btns[-1] + if self._calc_btns_width([cand] + sub_btns) <= avail_right_wing or not sub_btns: + sub_btns.insert(0, top_btns.pop()) + continue + if len(top_segs) > 1: + cand_s = top_segs[-1] + if self._calc_segs_width([cand_s] + sub_segs, pipe_step) <= avail_left_wing or not sub_segs: + sub_segs.insert(0, top_segs.pop()) + continue + break + + return top_segs, sub_segs, top_btns, sub_btns, pipe_ph, pipe_step + + def _get_bar_box_photo(self, box_key: str, w: int, h: int, scale: float = 0.80): + try: + return self.assets.get_box_photo(box_key, (w, h), border_scale=scale) + except TypeError: + return self.assets.get_box_photo(box_key, (w, h)) + def refresh_texts(self): - if self.winfo_exists() and self.winfo_width() >= 120: - self._draw_texts(self.winfo_width(), self.winfo_height()) + if not self.winfo_exists() or self.winfo_width() < 120: + return + w, h = self.winfo_width(), self.winfo_height() + _ts, _ss, top_b, sub_b, _pp, _ps = self._compute_partition(w) + cur_split = (tuple(id(b) for b in top_b), tuple(id(b) for b in sub_b)) + if cur_split != self._last_btn_split: + self._layout(w, h) + else: + self._render_partition(w, place_buttons=False) - def _layout(self, w: int, h: int): + def _layout(self, w: int, _h: int): self.delete("bb_frame") - side_inset = max(92, int(w * BG_SAFE_SIDE_RATIO)) frame_w = max(240, w - 2 * side_inset) cy = self.CONTENT_H // 2 - try: - self._frame_ph = self.assets.get_box_photo( - "box_gold_double", (frame_w, self.CONTENT_H - 2), border_scale=0.85 - ) - except TypeError: - self._frame_ph = self.assets.get_box_photo("box_gold_double", (frame_w, self.CONTENT_H - 2)) - + self._frame_ph = self._get_bar_box_photo( + "box_gold_double", frame_w, self.CONTENT_H - 2, scale=0.85 + ) if self._frame_ph: self.create_image(w // 2, cy, image=self._frame_ph, anchor="center", tags="bb_frame") - rx = w - side_inset - 16 - for btn in reversed(self._buttons): - bw = btn.pixel_width - bh = btn.pixel_height - btn.place(x=rx - bw, y=cy - bh // 2, width=bw, height=bh) - btn.lift() - rx -= (bw + 6) + self._render_partition(w, place_buttons=True) - self._btn_left_limit = rx - self._draw_texts(w, h) - - def _draw_texts(self, w: int, _h: int): + def _render_partition(self, w: int, place_buttons: bool = True): self.delete("bb_txt") + self.delete("bb_sub_frame") self._txt_refs.clear() + self._sub_left_frame_ph = None + self._sub_right_frame_ph = None + + top_segs, sub_segs, top_btns, sub_btns, pipe_ph, pipe_step = self._compute_partition(w) + self._txt_refs.append(pipe_ph) side_inset = max(92, int(w * BG_SAFE_SIDE_RATIO)) - cy = self.CONTENT_H // 2 - lx = side_inset + 18 - right_limit = self._btn_left_limit - 12 + cy_main = self.CONTENT_H // 2 + txt_cy_main = cy_main + self.HUD_TEXT_Y_OFFSET + sub_top = self.CONTENT_H + self.SUB_TOP_GAP + cy_sub = sub_top + self.SUB_BAR_H // 2 + txt_cy_sub = cy_sub + self.HUD_TEXT_Y_OFFSET - raw_hud = (self.hud_var.get() or "").replace("•", "-") - parts = [p.strip() for p in raw_hud.split("|") if p.strip()] + # 1. Hauptleisten-Buttons (oben rechts) + rx_main = w - side_inset - 16 + if place_buttons: + for btn in reversed(top_btns): + bw = btn.pixel_width + bh = btn.pixel_height + btn.place(x=rx_main - bw, y=cy_main - bh // 2, width=bw, height=bh) + tk.Widget.tkraise(btn) + rx_main -= (bw + 6) + else: + rx_main -= self._calc_btns_width(top_btns) - for i, seg in enumerate(parts): - txt = seg if i == 0 else f"- {seg}" - # Zeit-Segment nicht im Dauer-Cache verewigen, statische Segmente schon - if ":" in seg and any(ch.isdigit() for ch in seg): - try: - pil_seg = self.assets.render_goth_text_pil( - txt, size_px=FONT_SIZE_SMALL_MIN + 1, color=FONT_COLOR_HEADING_SUB, - align="left", uncached=True - ) - except TypeError: - pil_seg = self.assets.render_goth_text_pil( - txt, size_px=FONT_SIZE_SMALL_MIN + 1, color=FONT_COLOR_HEADING_SUB, align="left" - ) - seg_ph = ImageTk.PhotoImage(pil_seg) - else: - seg_ph = self.assets.get_goth_text_photo( - txt, size_px=FONT_SIZE_SMALL_MIN + 1, color=FONT_COLOR_HEADING_SUB, align="left" + # 2. Rechte Erweiterungsfläche (nur sichtbar, wenn Buttons nach unten ausgelagert wurden) + if sub_btns: + sub_btns_w = self._calc_btns_width(sub_btns) + r_box_w = sub_btns_w + 26 + r_box_right = w - side_inset + r_box_cx = r_box_right - r_box_w // 2 + + self.create_rectangle( + r_box_right - r_box_w + 4, + sub_top + 4, + r_box_right - 4, + sub_top + self.SUB_BAR_H - 4, + fill="#100d17", + outline="", + tags="bb_sub_frame", + ) + self._sub_right_frame_ph = self._get_bar_box_photo( + "box_gold_double", r_box_w, self.SUB_BAR_H, scale=0.72 + ) + if self._sub_right_frame_ph: + self.create_image( + r_box_cx, + cy_sub, + image=self._sub_right_frame_ph, + anchor="center", + tags="bb_sub_frame", ) - self._txt_refs.append(seg_ph) - self.create_image(lx, cy, image=seg_ph, anchor="w", tags="bb_txt") - lx += seg_ph.width() + 12 - st_str = (self.status_var.get() or "").replace("•", "-") - if st_str and (right_limit - lx) >= 80: + if place_buttons: + rx_sub = r_box_right - 13 + for btn in reversed(sub_btns): + bw = btn.pixel_width + bh = min(btn.pixel_height, self.SUB_BAR_H - 6) + btn.place(x=rx_sub - bw, y=cy_sub - bh // 2, width=bw, height=bh) + tk.Widget.tkraise(btn) + rx_sub -= (bw + 6) + + if place_buttons: + self._last_btn_split = ( + tuple(id(b) for b in top_btns), + tuple(id(b) for b in sub_btns), + ) + + # 3. Hauptleisten-Text im freien linken Bereich auf der X-Achse zentrieren + min_lx = side_inset + 22 + right_limit = rx_main - 14 + st_str = (self.status_var.get() or "").replace("•", "|") + + segs_w = self._calc_segs_width(top_segs, pipe_step) + st_ph = None + total_txt_w = segs_w + + if st_str and (right_limit - (min_lx + segs_w)) >= 90: + avail_st_w = right_limit - (min_lx + segs_w + (pipe_step if top_segs else 0)) st_ph = self.assets.get_goth_text_photo( st_str, size_px=FONT_SIZE_SMALL_MIN, color=UI_ACCENT_AMETHYST, - max_width=right_limit - lx, + max_width=max(80, avail_st_w), align="left", ) + total_txt_w += (pipe_step if top_segs else 0) + st_ph.width() + + avail_txt_span = max(0, right_limit - min_lx) + if total_txt_w > 0 and avail_txt_span > total_txt_w: + # Sanfte Zentrierung im freien Raum links neben den Buttons + centered_lx = min_lx + (avail_txt_span - total_txt_w) // 2 + self.HUD_TEXT_X_OFFSET + lx = max(min_lx, min(right_limit - total_txt_w, centered_lx)) + else: + lx = min_lx + self.HUD_TEXT_X_OFFSET + + for i, seg in enumerate(top_segs): + if i > 0: + self.create_image(lx + 5, txt_cy_main, image=pipe_ph, anchor="w", tags="bb_txt") + lx += pipe_step + ph = seg["photo"] + self._txt_refs.append(ph) + self.create_image(lx, txt_cy_main, image=ph, anchor="w", tags="bb_txt") + lx += ph.width() + + if st_ph is not None: + if top_segs: + self.create_image(lx + 6, txt_cy_main, image=pipe_ph, anchor="w", tags="bb_txt") + lx += pipe_step self._txt_refs.append(st_ph) - self.create_image(lx, cy, image=st_ph, anchor="w", tags="bb_txt") \ No newline at end of file + self.create_image(lx, txt_cy_main, image=st_ph, anchor="w", tags="bb_txt") + + # 4. Linke Erweiterungsfläche (nur sichtbar, wenn Text-Segmente nach unten ausgelagert wurden) + if sub_segs: + sub_txt_w = self._calc_segs_width(sub_segs, pipe_step) + l_box_w = sub_txt_w + 36 + l_box_left = side_inset + l_box_cx = l_box_left + l_box_w // 2 + + self.create_rectangle( + l_box_left + 4, + sub_top + 4, + l_box_left + l_box_w - 4, + sub_top + self.SUB_BAR_H - 4, + fill="#100d17", + outline="", + tags="bb_sub_frame", + ) + self._sub_left_frame_ph = self._get_bar_box_photo( + "box_gold_double", l_box_w, self.SUB_BAR_H, scale=0.72 + ) + if self._sub_left_frame_ph: + self.create_image( + l_box_cx, + cy_sub, + image=self._sub_left_frame_ph, + anchor="center", + tags="bb_sub_frame", + ) + + sub_lx = l_box_cx - sub_txt_w // 2 + for i, seg in enumerate(sub_segs): + if i > 0: + self.create_image(sub_lx + 5, txt_cy_sub, image=pipe_ph, anchor="w", tags="bb_txt") + sub_lx += pipe_step + ph = seg["photo"] + self._txt_refs.append(ph) + self.create_image(sub_lx, txt_cy_sub, image=ph, anchor="w", tags="bb_txt") + sub_lx += ph.width() \ No newline at end of file diff --git a/games/solitaire/base/solitaire_card.py b/games/solitaire/base/solitaire_card.py new file mode 100644 index 0000000..572070c --- /dev/null +++ b/games/solitaire/base/solitaire_card.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# games/solitaire/base/solitaire_card.py +from __future__ import annotations + +from dataclasses import dataclass + +from resources.code_res.game_constants import ( + CARD_FILE_PATTERN, + RED_SUITS, + SUIT_SYMBOLS, +) + +SOLITAIRE_RANKS: tuple[str, ...] = ( + "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" +) +RANK_VALUES: dict[str, int] = {rank: idx + 1 for idx, rank in enumerate(SOLITAIRE_RANKS)} + + +@dataclass +class SolitaireCard: + suit: str + rank: str + face_up: bool = False + deck_id: int = 0 + + @property + def value(self) -> int: + return RANK_VALUES[self.rank] + + @property + def is_red(self) -> bool: + return self.suit in RED_SUITS + + @property + def filename(self) -> str: + return CARD_FILE_PATTERN.format(suit=self.suit, rank=self.rank) + + @property + def label(self) -> str: + return f"{self.rank}{SUIT_SYMBOLS.get(self.suit, self.suit)}" + + def to_dict(self) -> dict: + return { + "s": self.suit, + "r": self.rank, + "u": 1 if self.face_up else 0, + "d": self.deck_id, + } + + @classmethod + def from_dict(cls, data: dict) -> SolitaireCard: + return cls( + suit=data["s"], + rank=data["r"], + face_up=bool(data.get("u", 0)), + deck_id=int(data.get("d", 0)), + ) \ No newline at end of file diff --git a/games/solitaire/base/solitaire_core.py b/games/solitaire/base/solitaire_core.py index f37b46d..5ff66f3 100644 --- a/games/solitaire/base/solitaire_core.py +++ b/games/solitaire/base/solitaire_core.py @@ -5,60 +5,23 @@ from __future__ import annotations import json import random import time -from dataclasses import dataclass -from resources.code_res.game_constants import ( - CARD_FILE_PATTERN, - RED_SUITS, - SUIT_SYMBOLS, - SUITS, +from games.solitaire.base.solitaire_card import ( + RANK_VALUES, + SOLITAIRE_RANKS, + SolitaireCard, ) +from resources.code_res.game_constants import SUITS -SOLITAIRE_RANKS: tuple[str, ...] = ( - "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" -) -RANK_VALUES: dict[str, int] = {rank: idx + 1 for idx, rank in enumerate(SOLITAIRE_RANKS)} - - -@dataclass -class SolitaireCard: - suit: str - rank: str - face_up: bool = False - deck_id: int = 0 - - @property - def value(self) -> int: - return RANK_VALUES[self.rank] - - @property - def is_red(self) -> bool: - return self.suit in RED_SUITS - - @property - def filename(self) -> str: - return CARD_FILE_PATTERN.format(suit=self.suit, rank=self.rank) - - @property - def label(self) -> str: - return f"{self.rank}{SUIT_SYMBOLS.get(self.suit, self.suit)}" - - def to_dict(self) -> dict: - return { - "s": self.suit, - "r": self.rank, - "u": 1 if self.face_up else 0, - "d": self.deck_id, - } - - @classmethod - def from_dict(cls, data: dict) -> SolitaireCard: - return cls( - suit=data["s"], - rank=data["r"], - face_up=bool(data.get("u", 0)), - deck_id=int(data.get("d", 0)), - ) +__all__ = [ + "SOLITAIRE_RANKS", + "RANK_VALUES", + "SolitaireCard", + "SolitaireBaseEngine", + "create_solitaire_deck", + "is_alternating_descending", + "is_same_suit_descending", +] def create_solitaire_deck( diff --git a/games/solitaire/freecell/views/__pycache__/freecell_table_view.cpython-311.pyc b/games/solitaire/freecell/views/__pycache__/freecell_table_view.cpython-311.pyc index b4d1274..070824f 100644 Binary files a/games/solitaire/freecell/views/__pycache__/freecell_table_view.cpython-311.pyc and b/games/solitaire/freecell/views/__pycache__/freecell_table_view.cpython-311.pyc differ diff --git a/games/solitaire/klondike/views/__pycache__/klondike_table_view.cpython-311.pyc b/games/solitaire/klondike/views/__pycache__/klondike_table_view.cpython-311.pyc index 9029cee..3fba8ec 100644 Binary files a/games/solitaire/klondike/views/__pycache__/klondike_table_view.cpython-311.pyc and b/games/solitaire/klondike/views/__pycache__/klondike_table_view.cpython-311.pyc differ diff --git a/games/solitaire/spider_solitaire/views/__pycache__/spider_table_view.cpython-311.pyc b/games/solitaire/spider_solitaire/views/__pycache__/spider_table_view.cpython-311.pyc index c11356a..a4350e7 100644 Binary files a/games/solitaire/spider_solitaire/views/__pycache__/spider_table_view.cpython-311.pyc and b/games/solitaire/spider_solitaire/views/__pycache__/spider_table_view.cpython-311.pyc differ diff --git a/resources/code_res/__pycache__/game_constants.cpython-311.pyc b/resources/code_res/__pycache__/game_constants.cpython-311.pyc index a7948f7..f12625c 100644 Binary files a/resources/code_res/__pycache__/game_constants.cpython-311.pyc and b/resources/code_res/__pycache__/game_constants.cpython-311.pyc differ diff --git a/resources/code_res/internal_base.db b/resources/code_res/internal_base.db index fde2fcb..6870f4f 100644 Binary files a/resources/code_res/internal_base.db and b/resources/code_res/internal_base.db differ diff --git a/resources/code_res/sql/01_allgemein.sql b/resources/code_res/sql/01_allgemein.sql index 8ded4ec..6175a83 100644 --- a/resources/code_res/sql/01_allgemein.sql +++ b/resources/code_res/sql/01_allgemein.sql @@ -293,7 +293,7 @@ INSERT INTO base_prestige_ranks (rank_idx, title_de, title_en) VALUES (259, 'Gottheit', 'Deity'); -- ========================================================================= --- ALLGEMEINE ÜBERSETZUNGEN (Menüs, Kategorien, Audio, Bots, Statistik) +-- ALLGEMEINE ÜBERSETZUNGEN (Menüs, Kategorien, Einstellungen, Bots, Statistik) -- ========================================================================= INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES @@ -315,6 +315,8 @@ INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES ('audio_test_btn', 'EN', 'Test Effect'), ('audio_title', 'DE', 'Audio & Atmosphäre'), ('audio_title', 'EN', 'Audio & Atmosphere'), +('bj_stats_select_acc_lbl', 'DE', 'Goldbeutel wählen:'), +('bj_stats_select_acc_lbl', 'EN', 'Select Gold Pouch:'), ('bot_default_name', 'DE', 'Kultist #{0}'), ('bot_default_name', 'EN', 'Cultist #{0}'), ('bot_level_0', 'DE', 'Stufe 0 – Verwirrte Seele (Zufall)'), @@ -333,12 +335,16 @@ INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES ('bot_level_6', 'EN', 'Level 6 – Deity (Merciless / Online Standard)'), ('btn_audio', 'DE', 'Audio'), ('btn_audio', 'EN', 'Audio'), +('btn_back', 'DE', '← Zurück'), +('btn_back', 'EN', '← Back'), ('btn_back_game_menu', 'DE', '← Spielmenü'), ('btn_back_game_menu', 'EN', '← Game Menu'), ('btn_back_main', 'DE', '← Hauptmenü'), ('btn_back_main', 'EN', '← Main Menu'), ('btn_lang', 'DE', 'Sprache: DE'), ('btn_lang', 'EN', 'Lang: EN'), +('btn_settings', 'DE', 'Einstellungen'), +('btn_settings', 'EN', 'Settings'), ('btn_stats', 'DE', 'Statistiken'), ('btn_stats', 'EN', 'Statistics'), ('btn_switch_profile', 'DE', '← Profil wechseln'), @@ -363,12 +369,14 @@ INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES ('choose_cardgame', 'EN', 'Choose a Card Game'), ('devils_deal_locked_badge', 'DE', '† DEVIL''S DEAL AKTIV — Flucht unmöglich'), ('devils_deal_locked_badge', 'EN', '† DEVIL''S DEAL ACTIVE — No Escape'), -('devils_deal_resume_card', 'DE', 'Pakt fortsetzen' || char(10) || '(Resume)'), -('devils_deal_resume_card', 'EN', 'Resume Pact' || char(10) || '(Continue)'), +('devils_deal_resume_card', 'DE', 'Pakt fortsetzen\n(Resume)'), +('devils_deal_resume_card', 'EN', 'Resume Pact\n(Continue)'), ('devils_deal_resume_desc', 'DE', 'Deine Seele ist an den Spieltisch gebunden. Andere Spiele sind gesperrt, bis der Pakt entschieden ist!'), ('devils_deal_resume_desc', 'EN', 'Your soul is bound to the table. Other games are locked until the pact is resolved!'), ('devils_deal_resume_title', 'DE', '† THE DEVIL''S DEAL AKTIV †'), ('devils_deal_resume_title', 'EN', '† THE DEVIL''S DEAL ACTIVE †'), +('filter_all_games', 'DE', 'Alle Spiele'), +('filter_all_games', 'EN', 'All Games'), ('header_title', 'DE', 'GOTH CARD COLLECTION'), ('header_title', 'EN', 'GOTH CARD COLLECTION'), ('level_badge', 'DE', '{0} • {1} (Lv. {2} | {3}/{4} XP)'), @@ -383,8 +391,8 @@ INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES ('main_acc_header', 'EN', '{0} • {1} (Lv. {2} | {3} XP)'), ('main_acc_soul_only', 'DE', 'Seele: {0}'), ('main_acc_soul_only', 'EN', 'Soul: {0}'), -('menu_card_rank_sub', 'DE', '{0}' || char(10) || 'Lv. {1}'), -('menu_card_rank_sub', 'EN', '{0}' || char(10) || 'Lv. {1}'), +('menu_card_rank_sub', 'DE', '{0}\nLv. {1}'), +('menu_card_rank_sub', 'EN', '{0}\nLv. {1}'), ('new_profile_btn', 'DE', 'Neuer Account'), ('new_profile_btn', 'EN', 'New Account'), ('no_games_found', 'DE', 'Noch keine start.py im Ordner games/ gefunden.'), @@ -411,15 +419,23 @@ INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES ('stat_win_pct', 'EN', 'Win Rate %'), ('stat_won', 'DE', 'Gewonnene Spiele'), ('stat_won', 'EN', 'Games Won'), +('stats_account_title', 'DE', 'Profil-Statistik: {0}'), +('stats_account_title', 'EN', 'Profile Statistics: {0}'), ('stats_all_variants_of_game', 'DE', 'Alle {0}-Spiele (Gesamt)'), ('stats_all_variants_of_game', 'EN', 'All {0} Games (Total)'), ('stats_game_board_title', 'DE', 'Statistik für {0}'), ('stats_game_board_title', 'EN', 'Statistics for {0}'), ('stats_game_rank_info', 'DE', 'Dein Rang in {0}: {1} • Stufe {2} ({3} / {4} XP)'), ('stats_game_rank_info', 'EN', 'Your Rank in {0}: {1} • Level {2} ({3} / {4} XP)'), +('stats_overall_summary', 'DE', 'Gesamtübersicht für Profil ''{0}'' (Alle Spiele)'), +('stats_overall_summary', 'EN', 'Overall Summary for Profile ''{0}'' (All Games)'), +('stats_pouch_lbl', 'DE', 'Konto:'), +('stats_pouch_lbl', 'EN', 'Pouch:'), +('stats_profile_total_tab', 'DE', 'Profil (Gesamt)'), +('stats_profile_total_tab', 'EN', 'Profile (Total)'), ('stats_select_game_lbl', 'DE', 'Spiel auswählen:'), ('stats_select_game_lbl', 'EN', 'Select Game:'), ('stats_view_topbar', 'DE', 'Spiel-Statistiken ({0})'), ('stats_view_topbar', 'EN', 'Game Statistics ({0})'), ('xp_next_level', 'DE', '{0} / {1} XP bis Lv. {2}'), -('xp_next_level', 'EN', '{0} / {1} XP to Lv. {2}'); +('xp_next_level', 'EN', '{0} / {1} XP to Lv. {2}'); \ No newline at end of file diff --git a/resources/code_res/sql/02_blackjack.sql b/resources/code_res/sql/02_blackjack.sql index 9f9834c..6eeb2bf 100644 --- a/resources/code_res/sql/02_blackjack.sql +++ b/resources/code_res/sql/02_blackjack.sql @@ -7,7 +7,7 @@ INSERT OR REPLACE INTO game_variants (id, folder_path, game_name, variant_key, d (102, 'blackjack', 'Blackjack', 'bj_highstakes', 'Blackjack - High Stakes'); -- ========================================================================= --- BLACKJACK (Konten, Tisch, Devil's Gambit, Showdown & Popups) +-- BLACKJACK (Konten, Tisch, Devil's Gambit, Showdown, Popups & Tooltips) -- ========================================================================= INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES @@ -37,14 +37,14 @@ INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES ('bj_bot_action_hit', 'EN', 'Draws card ({0})'), ('bj_bot_action_ready', 'DE', 'Fertig ({0} Karten)'), ('bj_bot_action_ready', 'EN', 'Ready ({0} cards)'), -('bj_bot_cards_hidden', 'DE', '{0} Karten • Pot: {1} Gold'), -('bj_bot_cards_hidden', 'EN', '{0} Cards • Pot: {1} Gold'), +('bj_bot_cards_hidden', 'DE', '{0} Karten | Pot: {1}g'), +('bj_bot_cards_hidden', 'EN', '{0} Cards | Pot: {1}g'), ('bj_bot_gold_lbl', 'DE', 'Beutel: {0} Gold'), ('bj_bot_gold_lbl', 'EN', 'Pouch: {0} Gold'), ('bj_bot_rebuy', 'DE', '{0} (Neukauf)'), ('bj_bot_rebuy', 'EN', '{0} (Rebuy)'), -('bj_bot_showdown_val', 'DE', '{0} Punkte • Einsatz: {1}'), -('bj_bot_showdown_val', 'EN', '{0} pts • Bet: {1}'), +('bj_bot_showdown_val', 'DE', '{0} Pkt. | Einsatz: {1}g'), +('bj_bot_showdown_val', 'EN', '{0} pts | Bet: {1}g'), ('bj_bot_turn_status', 'DE', '{0} überlegt...'), ('bj_bot_turn_status', 'EN', '{0} is acting...'), ('bj_bots_sec_title', 'DE', '2. Gegner am Tisch (Gold abzocken!)'), @@ -111,10 +111,12 @@ INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES ('bj_filter_all_tables', 'EN', 'This Account (All Blackjack Tables)'), ('bj_fold_btn', 'DE', 'Austreten'), ('bj_fold_btn', 'EN', 'Leave (Fold)'), +('bj_gold_display_lbl', 'DE', 'Guthaben: {0} Gold'), +('bj_gold_display_lbl', 'EN', 'Balance: {0} Gold'), ('bj_gold_display_none', 'DE', 'Kein aktives Konto'), ('bj_gold_display_none', 'EN', 'No active account'), -('bj_hand_box_title', 'DE', 'Hand {0}: {1}{2} • Pot: {3}g{4}'), -('bj_hand_box_title', 'EN', 'Hand {0}: {1}{2} • Pot: {3}g{4}'), +('bj_hand_box_title', 'DE', 'Hand {0}: {1}{2} | Pot: {3}g{4}'), +('bj_hand_box_title', 'EN', 'Hand {0}: {1}{2} | Pot: {3}g{4}'), ('bj_header_gold', 'DE', 'Konto ''{0}'': {1} Gold'), ('bj_header_gold', 'EN', 'Account ''{0}'': {1} Gold'), ('bj_hit_btn', 'DE', 'Karte ziehen (Hit)'), @@ -135,8 +137,8 @@ INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES ('bj_out_of_gold_table', 'EN', 'Account ''{0}'' only has {1} Gold left (Table minimum: {2} Gold).'), ('bj_player_title', 'DE', 'Deine Hand'), ('bj_player_title', 'EN', 'Your Hand'), -('bj_player_total', 'DE', 'Deine Hand: {0}{1} | Im Pot: {2} Gold{3}'), -('bj_player_total', 'EN', 'Your Hand: {0}{1} | In Pot: {2} Gold{3}'), +('bj_player_total', 'DE', 'Deine Hand: {0}{1} | Pot: {2}g{3}'), +('bj_player_total', 'EN', 'Your Hand: {0}{1} | Pot: {2}g{3}'), ('bj_popup_bank_gain', 'DE', 'Gewinn der Bank: +{0} Gold'), ('bj_popup_bank_gain', 'EN', 'House Profit: +{0} Gold'), ('bj_popup_bank_won', 'DE', 'Die Bank hat gewonnen'), @@ -163,8 +165,8 @@ INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES ('bj_popup_your_gain', 'EN', 'Your Profit: +{0} Gold'), ('bj_popup_your_loss', 'DE', 'Dein Verlust: -{0} Gold'), ('bj_popup_your_loss', 'EN', 'Your Loss: -{0} Gold'), -('bj_pot_banner', 'DE', 'GOLD-POT: {0} Gold | Höchsteinsatz am Tisch: {1} Gold'), -('bj_pot_banner', 'EN', 'GOLD POT: {0} Gold | Current Table Bet: {1} Gold'), +('bj_pot_banner', 'DE', 'GOLD-POT: {0} Gold'), +('bj_pot_banner', 'EN', 'GOLD POT: {0} Gold'), ('bj_pre_deal_prompt', 'DE', 'Bereit für die nächste Runde? Grundeinsatz beim Austeilen: {0} Gold pro Person.'), ('bj_pre_deal_prompt', 'EN', 'Ready for the next hand? Entry ante on deal: {0} Gold per player.'), ('bj_raise_lbl', 'DE', 'Erhöhen:'), @@ -217,16 +219,32 @@ INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES ('bj_soft_hint', 'EN', ' (Soft {0})'), ('bj_split_btn', 'DE', 'Teilen (+{0})'), ('bj_split_btn', 'EN', 'Split (+{0})'), -('bj_state_busted', 'DE', ' [OUT >21]'), -('bj_state_busted', 'EN', ' [OUT >21]'), -('bj_state_folded', 'DE', ' [RAUS]'), -('bj_state_folded', 'EN', ' [FOLDED]'), -('bj_state_locked', 'DE', ' [FERTIG]'), -('bj_state_locked', 'EN', ' [LOCKED]'), +('bj_state_busted', 'DE', ' [OUT >21]'), +('bj_state_busted', 'EN', ' [OUT >21]'), +('bj_state_folded', 'DE', ' [RAUS]'), +('bj_state_folded', 'EN', ' [FOLDED]'), +('bj_state_locked', 'DE', ' [FERTIG]'), +('bj_state_locked', 'EN', ' [LOCKED]'), ('bj_stats_acc_title', 'DE', 'Konto-Statistik: {0}'), ('bj_stats_acc_title', 'EN', 'Account Stats: {0}'), ('bj_stats_view_topbar', 'DE', 'Blackjack – Konto-Statistiken'), ('bj_stats_view_topbar', 'EN', 'Blackjack – Account Statistics'), +('bj_tip_call_yes', 'DE', 'Mitgehen: Den erhöhten Tischeinsatz begleichen, um mit dieser Hand im Rennen um den Gold-Pot zu bleiben.'), +('bj_tip_call_yes', 'EN', 'Match Bet: Pay the open table bet to keep this hand in contention for the Gold Pot.'), +('bj_tip_double', 'DE', 'Verdoppeln (Double Down): Deinen Einsatz verdoppeln und genau eine letzte Karte ziehen (danach stehen deine Karten fest).'), +('bj_tip_double', 'EN', 'Double Down: Double your current bet and draw exactly one final card (your hand is locked afterward).'), +('bj_tip_draw_no', 'DE', 'Keine Karte nehmen: Deinen aktuellen Punktestand in diesem Durchgang behalten, ohne Risiko dich über 21 zu kaufen.'), +('bj_tip_draw_no', 'EN', 'Stand / No Card: Keep your current score for this pass without risking a bust over 21.'), +('bj_tip_draw_yes', 'DE', 'Karte ziehen (Hit): Eine weitere Karte nehmen, um näher an 21 zu kommen (7-7-7 gewinnt sofort, über 21 ist überkauft).'), +('bj_tip_draw_yes', 'EN', 'Draw Card (Hit): Take another card to get closer to 21 (7-7-7 wins instantly, over 21 busts).'), +('bj_tip_fold', 'DE', 'Austreten: Diese Hand aufgeben. Bereits gesetztes Gold bleibt im Pot, du musst aber keine weiteren Erhöhungen mehr mitgehen.'), +('bj_tip_fold', 'EN', 'Leave Hand (Fold): Surrender this hand. Gold already in the pot stays there, with no further bets required.'), +('bj_tip_raise_chip', 'DE', 'Einsatz erhöhen: Zusätzliches Gold in den Pot legen und alle Gegner am Tisch zum Mitgehen oder Austreten zwingen.'), +('bj_tip_raise_chip', 'EN', 'Raise Bet: Add Gold to the pot, forcing all opponents at the table to match or fold.'), +('bj_tip_raise_no', 'DE', 'Nicht erhöhen: Ohne zusätzliche Einsatzerhöhung an den nächsten Spieler am Tisch weitergeben.'), +('bj_tip_raise_no', 'EN', 'No Raise: Pass the turn to the next seat without increasing the table bet.'), +('bj_tip_split', 'DE', 'Teilen (Split): Zwei gleichwertige Startkarten in zwei separate Hände aufteilen, die jeweils mit eigenem Einsatz um den Pot spielen.'), +('bj_tip_split', 'EN', 'Split: Divide two matching starting cards into two separate hands, each playing with its own stake.'), ('bj_tree_btn_call_no_lose', 'DE', 'Nein — Austreten (Verloren)'), ('bj_tree_btn_call_no_lose', 'EN', 'No — Leave (Lost)'), ('bj_tree_btn_call_yes', 'DE', 'Ja, Mitgehen (+{0} Gold)'), @@ -276,6 +294,4 @@ INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES ('variant_bj_classic', 'DE', 'Blackjack – Klassisch'), ('variant_bj_classic', 'EN', 'Blackjack – Classic'), ('variant_bj_highstakes', 'DE', 'Blackjack – Hoher Einsatz'), -('variant_bj_highstakes', 'EN', 'Blackjack – High Stakes'), -('bj_gold_display_lbl', 'DE', 'Guthaben: {0} Gold'), -('bj_gold_display_lbl', 'EN', 'Balance: {0} Gold'); \ No newline at end of file +('variant_bj_highstakes', 'EN', 'Blackjack – High Stakes'); \ No newline at end of file diff --git a/resources/code_res/sql/03_poker.sql b/resources/code_res/sql/03_poker.sql index a402472..f62d29b 100644 --- a/resources/code_res/sql/03_poker.sql +++ b/resources/code_res/sql/03_poker.sql @@ -15,6 +15,8 @@ INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES ('game_title_poker', 'EN', 'Texas Hold''em'), ('pk_acc_limit_info', 'DE', 'Max. {0} Goldbeutel. Blinds ab {1}/{2} Gold, No-Limit mit All-In & Side-Pots. Tausch: {3} XP → +{4} Gold.'), ('pk_acc_limit_info', 'EN', 'Max {0} Pouches. Blinds from {1}/{2} Gold, No-Limit with All-In & Side Pots. Exchange: {3} XP → +{4} Gold.'), +('pk_ante_status', 'DE', 'Grundeinsatz ({0}g)'), +('pk_ante_status', 'EN', 'Entry Ante ({0}g)'), ('pk_board_title', 'DE', 'Gemeinschaftskarten (Board)'), ('pk_board_title', 'EN', 'Community Cards (Board)'), ('pk_bot_act_allin', 'DE', 'ALL-IN! ({0}g)'), @@ -31,20 +33,24 @@ INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES ('pk_bot_act_raise', 'EN', 'Raises (+{0}g)'), ('pk_bot_act_sb', 'DE', 'Small Blind ({0}g)'), ('pk_bot_act_sb', 'EN', 'Small Blind ({0}g)'), -('pk_bot_stack_lbl', 'DE', 'Stack: {0}g • Einsatz: {1}g'), -('pk_bot_stack_lbl', 'EN', 'Stack: {0}g • Bet: {1}g'), +('pk_bot_stack_lbl', 'DE', 'Stack: {0}g | Einsatz: {1}g'), +('pk_bot_stack_lbl', 'EN', 'Stack: {0}g | Bet: {1}g'), ('pk_bot_turn_status', 'DE', '{0} überlegt...'), ('pk_bot_turn_status', 'EN', '{0} is thinking...'), ('pk_bots_sec_title', 'DE', '2. Gegner am 6-Max-Tisch (mind. 1 bis max. 5 Bots)'), ('pk_bots_sec_title', 'EN', '2. Opponents at 6-Max Table (min. 1 to max. 5 Bots)'), -('pk_btn_allin', 'DE', 'ALL-IN (+{0})'), -('pk_btn_allin', 'EN', 'ALL-IN (+{0})'), -('pk_btn_call', 'DE', 'Mitgehen (+{0})'), -('pk_btn_call', 'EN', 'Call (+{0})'), +('pk_btn_allin', 'DE', 'ALL-IN (+{0}g)'), +('pk_btn_allin', 'EN', 'ALL-IN (+{0}g)'), +('pk_btn_call', 'DE', 'Mitgehen (+{0}g)'), +('pk_btn_call', 'EN', 'Call (+{0}g)'), ('pk_btn_check', 'DE', 'Schieben (Check)'), ('pk_btn_check', 'EN', 'Check'), +('pk_btn_close_help', 'DE', 'Schließen'), +('pk_btn_close_help', 'EN', 'Close'), ('pk_btn_fold', 'DE', 'Passen (Fold)'), ('pk_btn_fold', 'EN', 'Fold'), +('pk_btn_hands_help', 'DE', 'Kartenreferenz'), +('pk_btn_hands_help', 'EN', 'Card Reference'), ('pk_default_acc_name', 'DE', 'Pokerbeutel #{0}'), ('pk_default_acc_name', 'EN', 'Poker Pouch #{0}'), ('pk_err_duplicate_name', 'DE', 'Ein Poker-Konto mit diesem Namen existiert bereits.'), @@ -53,6 +59,8 @@ INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES ('pk_err_need_one_bot', 'EN', 'At least 1 opponent must sit at a Poker table!'), ('pk_filter_all_tables', 'DE', 'Dieses Konto (Alle Poker-Tische)'), ('pk_filter_all_tables', 'EN', 'This Account (All Poker Tables)'), +('pk_gold_display_lbl', 'DE', 'Guthaben: {0} Gold'), +('pk_gold_display_lbl', 'EN', 'Balance: {0} Gold'), ('pk_gold_display_none', 'DE', 'Kein aktives Konto'), ('pk_gold_display_none', 'EN', 'No active account'), ('pk_hand_0', 'DE', 'Höchste Karte (High Card)'), @@ -105,10 +113,10 @@ INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES ('pk_menu_topbar', 'EN', 'Texas Hold''em – Accounts & 6-Max Table Selection'), ('pk_no_account_item', 'DE', '— Kein Pokerbeutel vorhanden —'), ('pk_no_account_item', 'EN', '— No Poker Pouch available —'), -('pk_player_bet_only', 'DE', 'Position:{0} | Runde: {1}g | Gesamt im Pot: {2}g{3}'), -('pk_player_bet_only', 'EN', 'Seat:{0} | Street: {1}g | Total in Pot: {2}g{3}'), -('pk_player_info', 'DE', 'Deine Hand: {0} | Runde: {1}g | Gesamt im Pot: {2}g{3}'), -('pk_player_info', 'EN', 'Your Hand: {0} | Street: {1}g | Total in Pot: {2}g{3}'), +('pk_player_bet_only', 'DE', 'Position:{0} | Runde: {1}g | Im Pot: {2}g{3}'), +('pk_player_bet_only', 'EN', 'Seat:{0} | Street: {1}g | In Pot: {2}g{3}'), +('pk_player_info', 'DE', 'Deine Hand: {0} | Runde: {1}g | Im Pot: {2}g{3}'), +('pk_player_info', 'EN', 'Your Hand: {0} | Street: {1}g | In Pot: {2}g{3}'), ('pk_popup_bot_gain', 'DE', 'Pot-Gewinn von {0}: +{1} Gold'), ('pk_popup_bot_gain', 'EN', 'Pot profit of {0}: +{1} Gold'), ('pk_popup_bot_won', 'DE', '{0} gewinnt ({1})'), @@ -119,8 +127,8 @@ INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES ('pk_popup_player_won', 'EN', 'You won the Pot! ({0})'), ('pk_popup_split_won', 'DE', 'Split-Pot gewonnen! ({0})'), ('pk_popup_split_won', 'EN', 'Split Pot Won! ({0})'), -('pk_pot_banner', 'DE', 'GESAMT-POT: {0} Gold | Phase: {1} | Aktueller Einsatz: {2} Gold'), -('pk_pot_banner', 'EN', 'TOTAL POT: {0} Gold | Street: {1} | Current Bet: {2} Gold'), +('pk_pot_banner', 'DE', 'GESAMT-POT: {0} Gold'), +('pk_pot_banner', 'EN', 'TOTAL POT: {0} Gold'), ('pk_raise_lbl', 'DE', 'Erhöhen +:'), ('pk_raise_lbl', 'EN', 'Raise +:'), ('pk_role_bb', 'DE', ' [BB]'), @@ -139,22 +147,22 @@ INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES ('pk_showdown_running', 'EN', 'Revealing remaining board cards — Showdown!'), ('pk_showdown_section_title', 'DE', 'Aufgedeckte Hände & Showdown'), ('pk_showdown_section_title', 'EN', 'Revealed Hands & Showdown'), -('pk_state_allin', 'DE', ' [ALL-IN]'), -('pk_state_allin', 'EN', ' [ALL-IN]'), -('pk_state_folded', 'DE', ' [GEPASST]'), -('pk_state_folded', 'EN', ' [FOLDED]'), +('pk_state_allin', 'DE', ' [ALL-IN]'), +('pk_state_allin', 'EN', ' [ALL-IN]'), +('pk_state_folded', 'DE', ' [GEPASST]'), +('pk_state_folded', 'EN', ' [FOLDED]'), ('pk_stats_view_topbar', 'DE', 'Texas Hold''em – Konto-Statistiken'), ('pk_stats_view_topbar', 'EN', 'Texas Hold''em – Account Statistics'), -('pk_street_FLOP', 'DE', 'Flop (3 Karten)'), -('pk_street_FLOP', 'EN', 'Flop (3 Cards)'), +('pk_street_FLOP', 'DE', 'Flop'), +('pk_street_FLOP', 'EN', 'Flop'), ('pk_street_PREFLOP', 'DE', 'Pre-Flop'), ('pk_street_PREFLOP', 'EN', 'Pre-Flop'), -('pk_street_RIVER', 'DE', 'River (5. Karte)'), -('pk_street_RIVER', 'EN', 'River (5th Card)'), +('pk_street_RIVER', 'DE', 'River'), +('pk_street_RIVER', 'EN', 'River'), ('pk_street_SHOWDOWN', 'DE', 'Showdown'), ('pk_street_SHOWDOWN', 'EN', 'Showdown'), -('pk_street_TURN', 'DE', 'Turn (4. Karte)'), -('pk_street_TURN', 'EN', 'Turn (4th Card)'), +('pk_street_TURN', 'DE', 'Turn'), +('pk_street_TURN', 'EN', 'Turn'), ('pk_tip_allin', 'DE', 'All-In: Deinen gesamten restlichen Goldbeutel setzen. Bei unterschiedlichen Stacks werden automatisch faire Side-Pots gebildet.'), ('pk_tip_allin', 'EN', 'All-In: Bet your entire remaining Gold pouch. Fair side pots are created automatically if stacks differ.'), ('pk_tip_call', 'DE', 'Mitgehen (Call): Den offenen Höchsteinsatz am Tisch begleichen, um im Pot zu bleiben.'), @@ -174,4 +182,4 @@ INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES ('variant_poker_holdem', 'DE', 'Texas Hold''em – Klassisch'), ('variant_poker_holdem', 'EN', 'Texas Hold''em – Classic'), ('variant_poker_holdem_high', 'DE', 'Texas Hold''em – Hoher Einsatz'), -('variant_poker_holdem_high', 'EN', 'Texas Hold''em – High Stakes'); +('variant_poker_holdem_high', 'EN', 'Texas Hold''em – High Stakes'); \ No newline at end of file diff --git a/resources/images/box_background.png b/resources/images/box_background.png new file mode 100644 index 0000000..bd4e52d Binary files /dev/null and b/resources/images/box_background.png differ diff --git a/resources/images/poker_table.jpg b/resources/images/poker_table.jpg deleted file mode 100644 index d28f349..0000000 Binary files a/resources/images/poker_table.jpg and /dev/null differ diff --git a/resources/images/switch_button_off.png b/resources/images/switch_button_off.png new file mode 100644 index 0000000..50ef957 Binary files /dev/null and b/resources/images/switch_button_off.png differ diff --git a/resources/images/switch_button_off_icon.png b/resources/images/switch_button_off_icon.png new file mode 100644 index 0000000..7e12294 Binary files /dev/null and b/resources/images/switch_button_off_icon.png differ diff --git a/resources/images/switch_button_on.png b/resources/images/switch_button_on.png new file mode 100644 index 0000000..936dd7f Binary files /dev/null and b/resources/images/switch_button_on.png differ diff --git a/resources/images/switch_button_on_icon.png b/resources/images/switch_button_on_icon.png new file mode 100644 index 0000000..d52efd8 Binary files /dev/null and b/resources/images/switch_button_on_icon.png differ diff --git a/view/__pycache__/assets_manager.cpython-311.pyc b/view/__pycache__/assets_manager.cpython-311.pyc index 05f3ab2..6cd8d91 100644 Binary files a/view/__pycache__/assets_manager.cpython-311.pyc and b/view/__pycache__/assets_manager.cpython-311.pyc differ diff --git a/view/__pycache__/main_window.cpython-311.pyc b/view/__pycache__/main_window.cpython-311.pyc index 2602132..67ab5d3 100644 Binary files a/view/__pycache__/main_window.cpython-311.pyc and b/view/__pycache__/main_window.cpython-311.pyc differ diff --git a/view/dialogs/__pycache__/audio_settings_dialog.cpython-311.pyc b/view/dialogs/__pycache__/audio_settings_dialog.cpython-311.pyc index 9ccf998..17628b9 100644 Binary files a/view/dialogs/__pycache__/audio_settings_dialog.cpython-311.pyc and b/view/dialogs/__pycache__/audio_settings_dialog.cpython-311.pyc differ diff --git a/view/dialogs/audio_settings_dialog.py b/view/dialogs/audio_settings_dialog.py index 4266634..aaa4059 100644 --- a/view/dialogs/audio_settings_dialog.py +++ b/view/dialogs/audio_settings_dialog.py @@ -20,29 +20,54 @@ from resources.code_res.game_constants import ( UI_ACCENT_GOLD, ) from resources.code_res.i18n import t -from view.widgets.image_button import ImageButton +from view.widgets.goth_switch import GothSwitch +from view.widgets.image_button import ( + ImageButton, + is_button_hover_help_enabled, + set_button_hover_help_enabled, +) + + +def is_german_active() -> bool: + lang_btn = t("btn_lang").upper() + return ("SPRACHE" in lang_btn) or lang_btn.endswith("DE") class AudioSettingsDialog(tk.Canvas): """ - Rahmenloses Gothic-Audio-Overlay auf Basis von background_vertical.jpg + box_big.png - mit eigenen Amethyst/Gold-Schiebereglern statt Standard-tk.Scale. + Rahmenloses Gothic-Einstellungs-Overlay: + - Sprache wechseln (DE / EN) + - Animierter Switch: 'Hilfe Texte bei Buttons Anzeigen' / 'Show Help Texts on Button Hover' + - Zwei Audio-Schieberegler (Ambiance & Soundeffekte) """ - DLG_W = 480 - DLG_H = 440 + DLG_W = 500 + DLG_H = 604 @classmethod - def open(cls, root_window: tk.Tk, assets, sound_mgr): + def open( + cls, + root_window: tk.Tk, + assets, + sound_mgr, + on_toggle_lang=None, + ): existing = getattr(root_window, "_audio_overlay", None) if existing and existing.winfo_exists(): - existing.lift() + existing.on_toggle_lang = on_toggle_lang or existing.on_toggle_lang + tk.Widget.tkraise(existing) return existing - dlg = cls(root_window, assets, sound_mgr) + dlg = cls(root_window, assets, sound_mgr, on_toggle_lang=on_toggle_lang) root_window._audio_overlay = dlg return dlg - def __init__(self, root_window: tk.Tk, assets, sound_mgr): + def __init__( + self, + root_window: tk.Tk, + assets, + sound_mgr, + on_toggle_lang=None, + ): super().__init__( root_window, width=self.DLG_W, @@ -54,26 +79,48 @@ class AudioSettingsDialog(tk.Canvas): self.root_window = root_window self.assets = assets self.sound_mgr = sound_mgr + self.on_toggle_lang = on_toggle_lang or self._resolve_fallback_lang_toggler() + self._bg_scaled_pil: Image.Image | None = None self._photo_refs: list[ImageTk.PhotoImage] = [] self._pct_photos: dict[str, ImageTk.PhotoImage] = {} self._dragging_key: str | None = None self._sliders: dict[str, dict] = {} self.place(relx=0.5, rely=0.5, anchor="center") + tk.Widget.tkraise(self) self._build_scene() + def _resolve_fallback_lang_toggler(self): + ctrl = getattr(self.root_window, "_app_controller", None) + if ctrl is not None and hasattr(ctrl, "toggle_language"): + return lambda: ctrl.toggle_language(None) + return None + + def _crop_dialog_bg_patch(self, cx: int, cy: int, pw: int, ph: int) -> ImageTk.PhotoImage | None: + if self._bg_scaled_pil is None: + return None + x1 = max(0, cx - pw // 2) + y1 = max(0, cy - ph // 2) + x2 = min(self.DLG_W, x1 + pw) + y2 = min(self.DLG_H, y1 + ph) + if x2 <= x1 or y2 <= y1: + return None + return ImageTk.PhotoImage(self._bg_scaled_pil.crop((x1, y1, x2, y2))) + def _build_scene(self): self.delete("all") self._photo_refs.clear() + self._sliders.clear() w, h = self.DLG_W, self.DLG_H + is_de = is_german_active() - # 1. Hochformat-Hintergrund (background_vertical.jpg) + box_big.png Zierrahmen + # 1. Hochformat-Hintergrund + box_big.png Zierrahmen bg_src = self.assets.raw_bg_vertical or self.assets.raw_bg_horizontal or self.assets.raw_bg if bg_src is not None: - bg_scaled = bg_src.resize((w, h), Image.Resampling.LANCZOS) - bg_ph = ImageTk.PhotoImage(bg_scaled) + self._bg_scaled_pil = bg_src.resize((w, h), Image.Resampling.LANCZOS) + bg_ph = ImageTk.PhotoImage(self._bg_scaled_pil) self._photo_refs.append(bg_ph) self.create_image(0, 0, image=bg_ph, anchor="nw") @@ -83,20 +130,39 @@ class AudioSettingsDialog(tk.Canvas): self.create_image(w // 2, h // 2, image=outer_box, anchor="center") # 2. Titel & Untertitel + dlg_title = "Einstellungen" if is_de else "Settings" + dlg_sub = ( + "Sprache, Bedienhilfen & Klangkulisse" + if is_de + else "Language, UI Helpers & Audio" + ) + title_ph = self.assets.get_goth_text_photo( - t("audio_title"), size_px=FONT_SIZE_TITLE_LG - 2, color=FONT_COLOR_TITLE_MAIN, max_width=w - 60 + dlg_title, + size_px=FONT_SIZE_TITLE_LG - 2, + color=FONT_COLOR_TITLE_MAIN, + max_width=w - 60, ) sub_ph = self.assets.get_goth_text_photo( - t("audio_subtitle"), size_px=FONT_SIZE_SMALL_MIN, color=FONT_COLOR_BODY_MUTED, max_width=w - 70 + dlg_sub, + size_px=FONT_SIZE_SMALL_MIN, + color=FONT_COLOR_BODY_MUTED, + max_width=w - 70, ) self._photo_refs.extend([title_ph, sub_ph]) - self.create_image(w // 2, 46, image=title_ph, anchor="center") - self.create_image(w // 2, 82, image=sub_ph, anchor="center") + self.create_image(w // 2, 40, image=title_ph, anchor="center") + self.create_image(w // 2, 70, image=sub_ph, anchor="center") - # 3. Zwei Slider-Boxen in box_small_purple.png + # 3. Sprach-Box + self._create_language_box(cy=128, is_de=is_de) + + # 4. Hover-Hilfetext-Switch-Box (mit animiertem GothSwitch) + self._create_hover_help_switch_box(cy=214, is_de=is_de) + + # 5. Zwei Audio-Slider-Boxen self._create_goth_slider( key="amb", - cy=162, + cy=320, label_txt=t("audio_ambiance_label"), desc_txt=t("audio_ambiance_desc"), initial_vol=self.sound_mgr.ambiance_volume, @@ -104,36 +170,182 @@ class AudioSettingsDialog(tk.Canvas): ) self._create_goth_slider( key="sfx", - cy=284, + cy=438, label_txt=t("audio_sfx_label"), desc_txt=t("audio_sfx_desc"), initial_vol=self.sound_mgr.menu_volume, on_change=lambda v: self.sound_mgr.set_menu_volume(v, persist=True), ) - # 4. Untere Aktions-Buttons (Amethyst für Test, Feuer für Fertig) + # 6. Untere Aktions-Buttons btn_norm = self.assets.raw_btn_default btn_purp = self.assets.raw_btn_purple btn_fire = self.assets.raw_btn_fire or btn_purp btn_test = ImageButton( - self, t("audio_test_btn"), btn_norm, btn_purp, + self, + t("audio_test_btn"), + btn_norm, + btn_purp, lambda: self.sound_mgr.play("deal"), - sound_mgr=None, width=168, height=40, style="amethyst" + sound_mgr=None, + width=168, + height=40, + style="amethyst", ) btn_done = ImageButton( - self, t("audio_done_btn"), btn_fire, btn_fire, - self.close, sound_mgr=self.sound_mgr, width=168, height=40, style="fire" + self, + t("audio_done_btn"), + btn_fire, + btn_fire, + self.close, + sound_mgr=self.sound_mgr, + width=168, + height=40, + style="fire", ) - self.create_window(42, h - 48, window=btn_test, anchor="w") - self.create_window(w - 42, h - 48, window=btn_done, anchor="e") + self.create_window(42, h - 46, window=btn_test, anchor="w") + self.create_window(w - 42, h - 46, window=btn_done, anchor="e") self.bind("", self._on_mouse_down) self.bind("", self._on_mouse_drag) self.bind("", lambda _e: setattr(self, "_dragging_key", None)) - def _create_goth_slider(self, key: str, cy: int, label_txt: str, desc_txt: str, initial_vol: float, on_change): - box_w, box_h = self.DLG_W - 72, 108 + def _create_language_box(self, cy: int, is_de: bool): + box_w, box_h = self.DLG_W - 72, 74 + cx = self.DLG_W // 2 + x_left = cx - box_w // 2 + 22 + x_right = cx + box_w // 2 - 20 + + sec_box = self.assets.get_box_photo("box_purple", (box_w, box_h)) + if sec_box: + self._photo_refs.append(sec_box) + self.create_image(cx, cy, image=sec_box, anchor="center") + + lang_heading = "Sprache" if is_de else "Language" + lang_desc = "Anzeigesprache wechseln" if is_de else "Switch display language" + + lbl_ph = self.assets.get_goth_text_photo( + lang_heading, + size_px=FONT_SIZE_HEADING - 4, + color=FONT_COLOR_BODY_DEFAULT, + align="left", + ) + desc_ph = self.assets.get_goth_text_photo( + lang_desc, + size_px=FONT_SIZE_SMALL_MIN, + color=FONT_COLOR_BODY_MUTED, + max_width=box_w - 180, + align="left", + ) + self._photo_refs.extend([lbl_ph, desc_ph]) + self.create_image(x_left, cy - 12, image=lbl_ph, anchor="w") + self.create_image(x_left, cy + 13, image=desc_ph, anchor="w") + + btn_norm = self.assets.raw_btn_default + btn_purp = self.assets.raw_btn_purple + lang_btn_txt = "Deutsch - EN" if is_de else "English - DE" + + btn_lang = ImageButton( + self, + lang_btn_txt, + btn_norm, + btn_purp, + self._handle_language_toggle, + sound_mgr=self.sound_mgr, + width=142, + height=34, + enabled=callable(self.on_toggle_lang), + style="amethyst", + ) + self.create_window(x_right, cy, window=btn_lang, anchor="e") + + def _create_hover_help_switch_box(self, cy: int, is_de: bool): + box_w, box_h = self.DLG_W - 72, 76 + cx = self.DLG_W // 2 + x_left = cx - box_w // 2 + 22 + x_right = cx + box_w // 2 - 20 + + sec_box = self.assets.get_box_photo("box_purple", (box_w, box_h)) + if sec_box: + self._photo_refs.append(sec_box) + self.create_image(cx, cy, image=sec_box, anchor="center") + + sw_title = ( + "Hilfe Texte bei Buttons Anzeigen" + if is_de + else "Show Help Texts on Button Hover" + ) + sw_desc = ( + "Erklärungen beim Überfahren von Aktions-Buttons" + if is_de + else "Display explanations when hovering action buttons" + ) + + lbl_ph = self.assets.get_goth_text_photo( + sw_title, + size_px=FONT_SIZE_BODY + 1, + color=FONT_COLOR_BODY_DEFAULT, + max_width=box_w - 144, + align="left", + ) + desc_ph = self.assets.get_goth_text_photo( + sw_desc, + size_px=FONT_SIZE_SMALL_MIN, + color=FONT_COLOR_BODY_MUTED, + max_width=box_w - 144, + align="left", + ) + self._photo_refs.extend([lbl_ph, desc_ph]) + self.create_image(x_left, cy - 12, image=lbl_ph, anchor="w") + self.create_image(x_left, cy + 14, image=desc_ph, anchor="w") + + sw_w, sw_h = 92, 40 + sw_cx = x_right - sw_w // 2 + patch_ph = self._crop_dialog_bg_patch(sw_cx, cy, sw_w, sw_h) + if patch_ph is not None: + self._photo_refs.append(patch_ph) + + switch_wgt = GothSwitch( + self, + value=is_button_hover_help_enabled(), + on_change=lambda state: set_button_hover_help_enabled(state, persist=True), + sound_mgr=self.sound_mgr, + width=sw_w, + height=sw_h, + bg_photo=patch_ph, + ) + self.create_window(x_right, cy, window=switch_wgt, anchor="e") + + def _handle_language_toggle(self): + if not callable(self.on_toggle_lang): + return + root = self.root_window + assets = self.assets + snd = self.sound_mgr + toggle_cb = self.on_toggle_lang + + self.close() + toggle_cb() + + if root.winfo_exists(): + root.after( + 15, + lambda: AudioSettingsDialog.open( + root, assets, snd, on_toggle_lang=toggle_cb + ), + ) + + def _create_goth_slider( + self, + key: str, + cy: int, + label_txt: str, + desc_txt: str, + initial_vol: float, + on_change, + ): + box_w, box_h = self.DLG_W - 72, 104 cx = self.DLG_W // 2 x_left = cx - box_w // 2 + 22 x_right = cx + box_w // 2 - 22 @@ -144,31 +356,49 @@ class AudioSettingsDialog(tk.Canvas): self.create_image(cx, cy, image=sec_box, anchor="center") lbl_ph = self.assets.get_goth_text_photo( - label_txt, size_px=FONT_SIZE_HEADING - 4, color=FONT_COLOR_BODY_DEFAULT, align="left" + label_txt, + size_px=FONT_SIZE_HEADING - 4, + color=FONT_COLOR_BODY_DEFAULT, + align="left", ) desc_ph = self.assets.get_goth_text_photo( - desc_txt, size_px=FONT_SIZE_SMALL_MIN, color=FONT_COLOR_BODY_MUTED, max_width=box_w - 44, align="left" + desc_txt, + size_px=FONT_SIZE_SMALL_MIN, + color=FONT_COLOR_BODY_MUTED, + max_width=box_w - 44, + align="left", ) self._photo_refs.extend([lbl_ph, desc_ph]) - self.create_image(x_left, cy - 30, image=lbl_ph, anchor="w") + self.create_image(x_left, cy - 28, image=lbl_ph, anchor="w") self.create_image(x_left, cy - 4, image=desc_ph, anchor="w") - pct_item = self.create_image(x_right, cy - 30, anchor="e") + pct_item = self.create_image(x_right, cy - 28, anchor="e") - track_y = cy + 28 + track_y = cy + 26 track_x1 = x_left + 4 track_x2 = x_right - 4 self.create_rectangle( - track_x1, track_y - 4, track_x2, track_y + 4, - fill="#09070e", outline=SUBTLE_BORDER, width=1 + track_x1, + track_y - 4, + track_x2, + track_y + 4, + fill="#09070e", + outline=SUBTLE_BORDER, + width=1, ) fill_id = self.create_rectangle( - track_x1, track_y - 3, track_x1, track_y + 3, - fill=UI_ACCENT_AMETHYST, outline="" + track_x1, + track_y - 3, + track_x1, + track_y + 3, + fill=UI_ACCENT_AMETHYST, + outline="", ) knob_id = self.create_polygon( 0, 0, 0, 0, 0, 0, 0, 0, - fill=UI_ACCENT_GOLD, outline="#0d0b12", width=1 + fill=UI_ACCENT_GOLD, + outline="#0d0b12", + width=1, ) self._sliders[key] = { @@ -191,13 +421,15 @@ class AudioSettingsDialog(tk.Canvas): kx = s["x1"] + (s["x2"] - s["x1"]) * val ky = s["y"] self.coords(s["fill_id"], s["x1"] + 1, ky - 3, kx, ky + 3) - # Rautenförmiger Gold-Reglergriff r = 9 self.coords(s["knob_id"], kx, ky - r, kx + r, ky, kx, ky + r, kx - r, ky) pct_txt = f"{int(round(val * 100))} %" pct_ph = self.assets.get_goth_text_photo( - pct_txt, size_px=FONT_SIZE_BODY + 2, color=FONT_COLOR_HEADING_SUB, align="right" + pct_txt, + size_px=FONT_SIZE_BODY + 2, + color=FONT_COLOR_HEADING_SUB, + align="right", ) self._pct_photos[key] = pct_ph self.itemconfigure(s["pct_item"], image=pct_ph) @@ -220,5 +452,10 @@ class AudioSettingsDialog(tk.Canvas): self._update_slider_visual(self._dragging_key, ratio, notify=True) def close(self): - self.destroy() - self.root_window._audio_overlay = None \ No newline at end of file + if self.winfo_exists(): + self.destroy() + if getattr(self.root_window, "_audio_overlay", None) is self: + self.root_window._audio_overlay = None + + +SettingsDialog = AudioSettingsDialog \ No newline at end of file diff --git a/view/menu_views.py b/view/menu_views.py deleted file mode 100644 index 1f2f9ec..0000000 --- a/view/menu_views.py +++ /dev/null @@ -1,219 +0,0 @@ -# -*- coding: utf-8 -*- -# view/menu_views.py -import tkinter as tk -from tkinter import ttk -from PIL import Image, ImageEnhance, ImageTk - -from models.database import Database -from resources.code_res.game_constants import ( - ACCENT_GOLD, ACCENT_GOTH, BG_COLOR, BORDER_COLOR, FG_COLOR, - INPUT_BG, MENU_CARD_SIZE, MUTED_FG, PANEL_BG, SUBTLE_BORDER -) -from resources.code_res.i18n import t -from view.assets_manager import StatsBoardWidget, create_img_button, show_audio_settings_overlay - - -class MenuViews: - def __init__(self, root_view): - self.root = root_view - self.ctrl = root_view.ctrl - self.assets = root_view.assets - self.sounds = root_view.ctrl.sounds - - self.profile_var = None - self.new_name_var = None - self._card_refs = [] - self._setup_styles() - - def _setup_styles(self): - style = ttk.Style() - style.theme_use("clam") - style.configure( - "Goth.TCombobox", - fieldbackground=INPUT_BG, - background=PANEL_BG, - foreground=FG_COLOR, - darkcolor=INPUT_BG, - lightcolor=INPUT_BG, - bordercolor=BORDER_COLOR, - arrowcolor=ACCENT_GOTH, - ) - style.map( - "Goth.TCombobox", - fieldbackground=[("readonly", INPUT_BG)], - foreground=[("readonly", FG_COLOR)], - ) - style.configure( - "Goth.Horizontal.TProgressbar", - troughcolor=BG_COLOR, - background=ACCENT_GOTH, - bordercolor=SUBTLE_BORDER, - lightcolor=ACCENT_GOTH, - darkcolor=ACCENT_GOTH, - ) - - def show_login(self, profiles: list[str], preselect_name: str = ""): - self.root.clear_window(apply_global_bg=True) - self._card_refs.clear() - - top_controls = tk.Frame(self.root, bg=BG_COLOR) - top_controls.place(relx=0.97, rely=0.04, anchor="ne") - - create_img_button( - top_controls, t("btn_lang"), self.assets.raw_sel, self.assets.raw_sel_active, - lambda: self.ctrl.toggle_language(), sound_mgr=self.sounds, width=85, height=36, font=("Helvetica", 10, "bold") - ).pack(side="left", padx=(0, 8)) - - create_img_button( - top_controls, t("btn_audio"), self.assets.raw_sel, self.assets.raw_sel_active, - lambda: show_audio_settings_overlay(self.root, self.assets, self.sounds), - sound_mgr=self.sounds, width=105, height=36, font=("Helvetica", 10, "bold") - ).pack(side="left") - - main_frame = tk.Frame(self.root, bg=BG_COLOR, padx=35, pady=30, highlightthickness=1, highlightbackground=SUBTLE_BORDER) - main_frame.place(relx=0.5, rely=0.5, anchor="center") - - title_photo = self.assets.get_scaled_photo("title_login", self.assets.raw_title, (360, 90)) - if title_photo: - tk.Label(main_frame, image=title_photo, bg=BG_COLOR, bd=0).pack(pady=(0, 15)) - else: - tk.Label(main_frame, text=t("app_title").upper(), font=("Georgia", 22, "bold"), fg=ACCENT_GOTH, bg=BG_COLOR).pack(pady=(0, 15)) - - if profiles: - frame = tk.Frame(main_frame, bg=BG_COLOR) - frame.pack(pady=10) - initial_prof = preselect_name if preselect_name in profiles else profiles[0] - self.profile_var = tk.StringVar(value=initial_prof) - cb = ttk.Combobox( - frame, textvariable=self.profile_var, values=profiles, - state="readonly", font=("Helvetica", 12), width=18, style="Goth.TCombobox" - ) - cb.grid(row=0, column=0, padx=10) - create_img_button( - frame, t("login_btn"), self.assets.raw_btn, self.assets.raw_btn_active, - lambda: self.ctrl.do_login(self.profile_var.get()), sound_mgr=self.sounds, width=155 - ).grid(row=0, column=1) - - tk.Frame(main_frame, bg=SUBTLE_BORDER, height=1).pack(fill="x", padx=20, pady=15) - - new_frame = tk.Frame(main_frame, bg=BG_COLOR) - new_frame.pack(pady=8) - self.new_name_var = tk.StringVar() - entry = tk.Entry( - new_frame, textvariable=self.new_name_var, font=("Helvetica", 13), - bg=INPUT_BG, fg=FG_COLOR, bd=0, width=19, - highlightthickness=1, highlightbackground=BORDER_COLOR, insertbackground="white" - ) - entry.grid(row=0, column=0, padx=10, ipady=6) - entry.bind("", lambda e: self.ctrl.do_create_profile(self.new_name_var.get().strip())) - - create_img_button( - new_frame, t("new_profile_btn"), self.assets.raw_btn, self.assets.raw_btn_active, - lambda: self.ctrl.do_create_profile(self.new_name_var.get().strip()), sound_mgr=self.sounds, width=155 - ).grid(row=0, column=1) - - def show_main_menu(self, profile: dict, available_games: list[dict]): - self.root.clear_window(apply_global_bg=True) - self._card_refs.clear() - - container = tk.Frame(self.root, bg=BG_COLOR, padx=24, pady=16) - container.place(relx=0.5, rely=0.5, anchor="center", relwidth=0.93, relheight=0.93) - - top_bar = tk.Frame(container, bg=BG_COLOR) - top_bar.pack(fill="x", pady=(0, 8)) - - left_btns = tk.Frame(top_bar, bg=BG_COLOR) - left_btns.pack(side="left") - - create_img_button( - left_btns, t("btn_switch_profile"), self.assets.raw_sel, self.assets.raw_sel_active, - self.ctrl.logout_to_login, sound_mgr=self.sounds, width=155, height=38, font=("Helvetica", 10, "bold") - ).pack(side="left", padx=(0, 6)) - - create_img_button( - left_btns, t("btn_lang"), self.assets.raw_sel, self.assets.raw_sel_active, - lambda: self.ctrl.toggle_language(), sound_mgr=self.sounds, width=82, height=38, font=("Helvetica", 10, "bold") - ).pack(side="left", padx=(0, 6)) - - create_img_button( - left_btns, t("btn_audio"), self.assets.raw_sel, self.assets.raw_sel_active, - lambda: show_audio_settings_overlay(self.root, self.assets, self.sounds), - sound_mgr=self.sounds, width=100, height=38, font=("Helvetica", 10, "bold") - ).pack(side="left") - - tk.Label(top_bar, text=t("header_title"), font=("Georgia", 20, "bold"), fg=ACCENT_GOTH, bg=BG_COLOR).pack(side="left", expand=True) - - acc_box = tk.Frame(top_bar, bg=PANEL_BG, padx=14, pady=6, highlightthickness=1, highlightbackground=BORDER_COLOR) - acc_box.pack(side="right") - - tk.Label( - acc_box, - text=t("main_acc_header", profile["name"], profile["level"], profile["total_points"]), - font=("Helvetica", 11, "bold"), fg=ACCENT_GOLD, bg=PANEL_BG - ).pack(anchor="e") - - xp_row = tk.Frame(acc_box, bg=PANEL_BG) - xp_row.pack(fill="x", pady=(3, 0)) - ttk.Progressbar( - xp_row, style="Goth.Horizontal.TProgressbar", - orient="horizontal", length=150, mode="determinate", - maximum=profile["needed_xp"], value=profile["current_xp"] - ).pack(side="left", padx=(0, 8)) - tk.Label( - xp_row, text=t("xp_next_level", profile["current_xp"], profile["needed_xp"], profile["level"] + 1), - font=("Helvetica", 8), fg=MUTED_FG, bg=PANEL_BG - ).pack(side="right") - - # Spiel-Karten - cards_section = tk.Frame(container, bg=BG_COLOR) - cards_section.pack(fill="both", expand=True, pady=6) - tk.Label(cards_section, text=t("choose_cardgame"), font=("Helvetica", 12, "bold"), fg=FG_COLOR, bg=BG_COLOR).pack(pady=(0, 6)) - - cards_grid = tk.Frame(cards_section, bg=BG_COLOR) - cards_grid.pack(expand=True) - - if not available_games: - tk.Label(cards_grid, text=t("no_games_found"), font=("Helvetica", 12), fg=MUTED_FG, bg=BG_COLOR).pack(pady=30) - else: - for idx, game in enumerate(available_games): - card_widget = self._create_game_card(cards_grid, game["title"], lambda g=game: self.ctrl.launch_game(g)) - card_widget.grid(row=idx // 4, column=idx % 4, padx=14, pady=8) - - # Statistik-Übersicht - variants = Database.get_variants_for_filter() - filter_map = {t("filter_all_games"): None} - for v in variants: - filter_map[v["translated_name"]] = v["id"] - - StatsBoardWidget( - container, - title=t("stats_account_title", profile["name"]), - filter_map=filter_map, - fetch_callback=lambda vid: Database.get_stats_overview(profile["id"], vid) - ).pack(fill="x", side="bottom", pady=(8, 0)) - - def _create_game_card(self, parent, game_title: str, on_click) -> tk.Canvas: - card_w, card_h = MENU_CARD_SIZE - cv = tk.Canvas(parent, width=card_w, height=card_h, bg=BG_COLOR, highlightthickness=0, cursor="hand2") - - normal_img = hover_img = None - if self.assets.raw_chat_frame: - base = self.assets.raw_chat_frame.resize((card_w, card_h), Image.Resampling.LANCZOS) - bright = ImageEnhance.Brightness(base).enhance(1.22) - normal_img = ImageTk.PhotoImage(base) - hover_img = ImageTk.PhotoImage(bright) - self._card_refs.extend([normal_img, hover_img]) - bg_id = cv.create_image(0, 0, image=normal_img, anchor="nw") - else: - bg_id = cv.create_rectangle(4, 4, card_w - 4, card_h - 4, fill=PANEL_BG, outline=ACCENT_GOTH, width=2) - - txt_id = cv.create_text( - card_w // 2, card_h // 2, - text=game_title, width=card_w - 36, justify="center", - font=("Georgia", 15, "bold"), fill=FG_COLOR - ) - - cv.bind("", lambda e: (cv.itemconfigure(bg_id, image=hover_img) if hover_img else None, cv.itemconfigure(txt_id, fill=ACCENT_GOLD))) - cv.bind("", lambda e: (cv.itemconfigure(bg_id, image=normal_img) if normal_img else None, cv.itemconfigure(txt_id, fill=FG_COLOR))) - cv.bind("", lambda e: (self.sounds.play("click"), on_click())) - return cv \ No newline at end of file diff --git a/view/unified_stats_view.py b/view/unified_stats_view.py new file mode 100644 index 0000000..be35192 --- /dev/null +++ b/view/unified_stats_view.py @@ -0,0 +1,551 @@ +# -*- coding: utf-8 -*- +# view/unified_stats_view.py +from __future__ import annotations + +import tkinter as tk +from PIL import Image, ImageTk + +from models.database import Database +from resources.code_res.game_constants import ( + BG_COLOR, + FONT_COLOR_BODY_DEFAULT, + FONT_COLOR_BODY_MUTED, + FONT_COLOR_HEADING_SUB, + FONT_COLOR_STATUS_LOSS, + FONT_COLOR_STATUS_WIN, + FONT_COLOR_TITLE_MAIN, + FONT_SIZE_BODY, + FONT_SIZE_HEADING, + FONT_SIZE_SMALL_MIN, + STAT_FIELD_KEYS, + STAT_GAME_GROUPS, +) +from resources.code_res.i18n import t +from view.widgets.goth_dropdown import GothDropdown +from view.widgets.image_button import ImageButton + +SHORT_VARIANT_TAB_KEYS: dict[str, str] = { + "klondike_1": "kl_draw_toggle_1", + "klondike_3": "kl_draw_toggle_3", + "spider_1suit": "sp_suit_toggle_1", + "spider_2suit": "sp_suit_toggle_2", + "spider_4suit": "sp_suit_toggle_4", +} + +ENDPOINT_ALIASES: dict[str, str | None] = { + "": None, + "all": None, + "gesamt": None, + "blackjack": "blackjack", + "poker": "poker", + "klondike": "solitaire/klondike", + "solitaire/klondike": "solitaire/klondike", + "freecell": "solitaire/freecell", + "solitaire/freecell": "solitaire/freecell", + "spider": "solitaire/spider_solitaire", + "spider_solitaire": "solitaire/spider_solitaire", + "solitaire/spider_solitaire": "solitaire/spider_solitaire", +} + + +def resolve_stats_endpoint(endpoint: str | None) -> str | None: + """Löst Kurznamen wie 'klondike', 'spider' oder 'blackjack' auf den DB-Ordnerpfad auf.""" + if endpoint is None: + return None + clean = str(endpoint).strip().lower() + if clean in ENDPOINT_ALIASES: + return ENDPOINT_ALIASES[clean] + + valid_folders = [folder for folder, _tkey in STAT_GAME_GROUPS] + if clean in valid_folders: + return clean + for f in valid_folders: + if f.endswith(f"/{clean}") or clean in f: + return f + return None + + +class UnifiedStatsView(tk.Canvas): + """ + Zentrale Vollbild-Statistik-Ansicht für alle Spiele (ohne Topbar & ohne Bottombar): + - Parameter 1 (`game_endpoint`): Spiel-Endpunkt ('blackjack', 'poker', 'klondike', 'freecell', 'spider' oder None) + - Parameter 2 (`on_back`): Optionale Rücksprung-Funktion; falls None, schließt sich das Overlay + einfach und gibt die exakt darunterliegende Spielansicht sofort wieder frei! + """ + + @classmethod + def open( + cls, + context, + game_endpoint: str | None = None, + on_back=None, + ) -> "UnifiedStatsView": + GothDropdown.close_any_open_popup() + root = context.root + existing = getattr(root, "_unified_stats_overlay", None) + if existing is not None and existing.winfo_exists(): + existing.destroy() + + view = cls(context, game_endpoint=game_endpoint, on_back=on_back) + setattr(root, "_unified_stats_overlay", view) + return view + + def __init__( + self, + context, + game_endpoint: str | None = None, + on_back=None, + ): + super().__init__( + context.root, + bg=BG_COLOR, + bd=0, + highlightthickness=0, + ) + self.ctx = context + self.on_back = on_back + + self._active_folder: str | None = resolve_stats_endpoint(game_endpoint) + self._active_variant_id: int | None = None + self._active_account_id: int | None = None + + self._bg_photo: ImageTk.PhotoImage | None = None + self._photo_refs: list = [] + self._child_buttons: list[ImageButton] = [] + self._esc_bind_id: str | None = None + + self.place(relx=0.0, rely=0.0, relwidth=1.0, relheight=1.0) + tk.Widget.tkraise(self) + + self.bind("", self._on_configure) + self.bind("", self._on_destroy) + try: + self._esc_bind_id = self.ctx.root.bind("", self._handle_back, add="+") + except tk.TclError: + self._esc_bind_id = None + + self._rebuild_view() + + def show( + self, + game_folder: str | None = None, + variant_id: int | None = None, + account_id: int | None = None, + ): + self._active_folder = resolve_stats_endpoint(game_folder) + self._active_variant_id = variant_id + self._active_account_id = account_id + self._rebuild_view() + + def _on_destroy(self, event=None): + if event is not None and event.widget is not self: + return + if self._esc_bind_id is not None: + try: + self.ctx.root.unbind("", self._esc_bind_id) + except Exception: + pass + self._esc_bind_id = None + if getattr(self.ctx.root, "_unified_stats_overlay", None) is self: + setattr(self.ctx.root, "_unified_stats_overlay", None) + + def _handle_back(self, _event=None): + back_cb = self.on_back + if self.winfo_exists(): + self.destroy() + if callable(back_cb): + back_cb() + return "break" + + def _switch_filter( + self, + folder: str | None, + variant_id: int | None = None, + account_id: int | None = None, + ): + self._active_folder = folder + self._active_variant_id = variant_id + self._active_account_id = account_id + self._rebuild_view() + + def _clear_buttons(self): + for b in self._child_buttons: + try: + if b.winfo_exists(): + b.destroy() + except Exception: + pass + self._child_buttons.clear() + + def _render_full_bg(self, w: int, h: int): + if hasattr(self.ctx.assets, "get_bg_patch_photo"): + self._bg_photo = self.ctx.assets.get_bg_patch_photo(w, h, 0, 0, w, h) + else: + src = ( + self.ctx.assets.raw_bg_vertical + if (h > w and self.ctx.assets.raw_bg_vertical is not None) + else (self.ctx.assets.raw_bg_horizontal or self.ctx.assets.raw_bg) + ) + if src is not None: + self._bg_photo = ImageTk.PhotoImage( + src.resize((w, h), Image.Resampling.BILINEAR) + ) + + if self._bg_photo is not None: + self.delete("stats_bg") + self.create_image(0, 0, image=self._bg_photo, anchor="nw", tags="stats_bg") + self.tag_lower("stats_bg") + + def _on_configure(self, event): + if event.widget is not self or event.width < 200 or event.height < 200: + return + self._draw_canvas_layout(event.width, event.height) + + def _rebuild_view(self): + if not self.winfo_exists(): + return + self._clear_buttons() + + pid = self.ctx.profile["id"] + + btn_norm = self.ctx.assets.raw_btn_default + btn_purp = self.ctx.assets.raw_btn_purple + btn_fire = self.ctx.assets.raw_btn_fire or btn_purp + + self._back_btn = ImageButton( + self, + t("btn_back"), + btn_fire, + btn_fire, + self._handle_back, + sound_mgr=self.ctx.sounds, + width=118, + height=34, + style="fire", + ) + self._child_buttons.append(self._back_btn) + + # 1. Spiel-Umschalter (Alle Spiele + registrierte Spiele) + all_lbl = t("filter_all_games") + game_tabs: list[tuple[str | None, str]] = [(None, all_lbl)] + for folder_key, title_i18n_key in STAT_GAME_GROUPS: + game_tabs.append((folder_key, t(title_i18n_key))) + + self._game_btns: list[tuple[ImageButton, int]] = [] + for f_key, g_lbl in game_tabs: + is_sel = (self._active_folder == f_key) + bw = max(108, min(162, len(g_lbl) * 9 + 34)) + b = ImageButton( + self, + g_lbl, + btn_fire if is_sel else btn_norm, + btn_fire if is_sel else btn_purp, + lambda target_f=f_key: self._switch_filter(target_f, None, None), + sound_mgr=self.ctx.sounds, + width=bw, + height=34, + style="fire" if is_sel else "amethyst", + ) + self._child_buttons.append(b) + self._game_btns.append((b, b.pixel_width)) + + # 2. Goldbeutel-Umschalter (nur bei Blackjack & Poker) + self._acc_btns: list[tuple[ImageButton, int]] = [] + accounts: list[dict] = [] + active_acc_obj: dict | None = None + if self._active_folder == "blackjack": + accounts = Database.get_blackjack_accounts(pid) + elif self._active_folder == "poker": + accounts = Database.get_poker_accounts(pid) + + if accounts: + for a in accounts: + if a["id"] == self._active_account_id: + active_acc_obj = a + break + if self._active_account_id is not None and active_acc_obj is None: + self._active_account_id = None + + prof_all_lbl = t("stats_profile_total_tab") + is_prof_sel = (active_acc_obj is None) + b_prof = ImageButton( + self, + prof_all_lbl, + btn_fire if is_prof_sel else btn_norm, + btn_fire if is_prof_sel else btn_purp, + lambda: self._switch_filter( + self._active_folder, self._active_variant_id, None + ), + sound_mgr=self.ctx.sounds, + width=142, + height=32, + style="fire" if is_prof_sel else "amethyst", + ) + self._child_buttons.append(b_prof) + self._acc_btns.append((b_prof, b_prof.pixel_width)) + + for acc in accounts: + is_a_sel = (active_acc_obj is not None and acc["id"] == active_acc_obj["id"]) + a_lbl = f"{acc['account_name']} ({acc['gold']}g)" + bw_a = max(136, min(195, len(a_lbl) * 8 + 30)) + b_acc = ImageButton( + self, + a_lbl, + btn_fire if is_a_sel else btn_norm, + btn_fire if is_a_sel else btn_purp, + lambda aid=acc["id"]: self._switch_filter( + self._active_folder, self._active_variant_id, aid + ), + sound_mgr=self.ctx.sounds, + width=bw_a, + height=32, + style="fire" if is_a_sel else "amethyst", + ) + self._child_buttons.append(b_acc) + self._acc_btns.append((b_acc, b_acc.pixel_width)) + + # 3. Varianten-Umschalter (sofern das Spiel mehrere Varianten hat) + self._var_btns: list[tuple[ImageButton, int]] = [] + variants = ( + Database.get_variants_for_filter(self._active_folder) + if self._active_folder + else [] + ) + if len(variants) > 1: + v_tabs: list[tuple[int | None, str]] = [(None, t("sol_stats_tab_all"))] + for v in variants: + vk = v["variant_key"] + short_lbl = ( + t(SHORT_VARIANT_TAB_KEYS[vk]) + if vk in SHORT_VARIANT_TAB_KEYS + else v["translated_name"] + ) + v_tabs.append((v["id"], short_lbl)) + + for vid, v_text in v_tabs: + is_vsel = (self._active_variant_id == vid) + bw_v = 110 if vid is None else max(136, min(190, len(v_text) * 8 + 28)) + b_var = ImageButton( + self, + v_text, + btn_fire if is_vsel else btn_norm, + btn_fire if is_vsel else btn_purp, + lambda target_vid=vid: self._switch_filter( + self._active_folder, target_vid, self._active_account_id + ), + sound_mgr=self.ctx.sounds, + width=bw_v, + height=32, + style="fire" if is_vsel else "amethyst", + ) + self._child_buttons.append(b_var) + self._var_btns.append((b_var, b_var.pixel_width)) + + # 4. Datenabfrage + if self._active_folder is None: + self._rank_line = t("stats_overall_summary", self.ctx.profile["name"]) + self._board_heading = all_lbl + self._stats_data = Database.get_stats_overview(pid, variant_id=None, folder_path=None) + else: + group_map = dict(STAT_GAME_GROUPS) + game_name = ( + t(group_map[self._active_folder]) + if self._active_folder in group_map + else self._active_folder + ) + prog = Database.get_game_progress(pid, self._active_folder) + self._rank_line = t( + "stats_game_rank_info", + game_name, + prog["title"], + prog["level"], + prog["current_xp"], + prog["needed_xp"], + ) + + var_label = t("stats_all_variants_of_game", game_name) + for v in variants: + if v["id"] == self._active_variant_id: + var_label = v["translated_name"] + break + + if active_acc_obj is not None and self._active_folder == "blackjack": + self._board_heading = ( + f"{t('bj_stats_acc_title', active_acc_obj['account_name'])} | {var_label}" + ) + self._stats_data = Database.get_bj_account_stats_overview( + active_acc_obj["id"], self._active_variant_id + ) + elif active_acc_obj is not None and self._active_folder == "poker": + self._board_heading = ( + f"{t('bj_stats_acc_title', active_acc_obj['account_name'])} | {var_label}" + ) + self._stats_data = Database.get_pk_account_stats_overview( + active_acc_obj["id"], self._active_variant_id + ) + else: + self._board_heading = t("stats_game_board_title", var_label) + self._stats_data = Database.get_stats_overview( + pid, + variant_id=self._active_variant_id, + folder_path=self._active_folder if self._active_variant_id is None else None, + ) + + self.ctx.root.update_idletasks() + w = max(900, self.winfo_width(), self.ctx.root.winfo_width()) + h = max(620, self.winfo_height(), self.ctx.root.winfo_height()) + self._draw_canvas_layout(w, h) + + def _draw_canvas_layout(self, w: int, h: int): + self._render_full_bg(w, h) + self.delete("fg") + self._photo_refs.clear() + + pad_x = max(92, int(w * 0.088)) + content_w = min(1080, w - 2 * pad_x) + left_x = (w - content_w) // 2 + + top_btn_cy = max(48, int(h * 0.068)) + self.create_window(left_x, top_btn_cy, window=self._back_btn, anchor="w", tags="fg") + + hdr_ph = self.ctx.assets.get_goth_text_photo( + t("btn_stats"), + size_px=FONT_SIZE_HEADING - 1, + color=FONT_COLOR_TITLE_MAIN, + align="right", + ) + self._photo_refs.append(hdr_ph) + self.create_image( + left_x + content_w, top_btn_cy, image=hdr_ph, anchor="e", tags="fg" + ) + + cur_y = max(top_btn_cy + 30, int(h * 0.125)) + + nav_h = 58 + nav_cy = cur_y + nav_h // 2 + nav_box = self.ctx.assets.get_box_photo("box_gold_double", (content_w, nav_h)) + if nav_box: + self._photo_refs.append(nav_box) + self.create_image(w // 2, nav_cy, image=nav_box, anchor="center", tags="fg") + + total_gb_w = sum(bw for _, bw in self._game_btns) + max(0, len(self._game_btns) - 1) * 8 + gx = w // 2 - total_gb_w // 2 + for b_wgt, bw in self._game_btns: + self.create_window(gx, nav_cy, window=b_wgt, anchor="w", tags="fg") + gx += bw + 8 + + cur_y += nav_h + 14 + + has_acc_row = len(self._acc_btns) > 0 + hdr_h = 104 if has_acc_row else 64 + hdr_cy = cur_y + hdr_h // 2 + hdr_box = self.ctx.assets.get_box_photo("box_purple", (content_w, hdr_h)) + if hdr_box: + self._photo_refs.append(hdr_box) + self.create_image(w // 2, hdr_cy, image=hdr_box, anchor="center", tags="fg") + + var_row_w = sum(bw + 6 for _, bw in self._var_btns) + top_row_y = (cur_y + 28) if has_acc_row else hdr_cy + + rank_ph = self.ctx.assets.get_goth_text_photo( + self._rank_line, + size_px=FONT_SIZE_BODY + 1, + color=FONT_COLOR_TITLE_MAIN, + max_width=max(220, content_w - var_row_w - 56), + align="left", + ) + self._photo_refs.append(rank_ph) + self.create_image(left_x + 24, top_row_y, image=rank_ph, anchor="w", tags="fg") + + rx = left_x + content_w - 22 + for b_wgt, bw in reversed(self._var_btns): + self.create_window(rx, top_row_y, window=b_wgt, anchor="e", tags="fg") + rx -= (bw + 6) + + if has_acc_row: + acc_row_y = cur_y + hdr_h - 26 + ax = left_x + 24 + p_ph = self.ctx.assets.get_goth_text_photo( + t("stats_pouch_lbl"), + size_px=FONT_SIZE_BODY, + color=FONT_COLOR_HEADING_SUB, + align="left", + ) + self._photo_refs.append(p_ph) + self.create_image(ax, acc_row_y, image=p_ph, anchor="w", tags="fg") + ax += p_ph.width() + 14 + + for b_wgt, bw in self._acc_btns: + self.create_window(ax, acc_row_y, window=b_wgt, anchor="w", tags="fg") + ax += bw + 8 + + cur_y += hdr_h + 14 + + bottom_safe = max(58, int(h * 0.095)) + board_h = max(246, min(350, h - cur_y - bottom_safe)) + board_cy = cur_y + board_h // 2 + + outer_box = self.ctx.assets.get_box_photo("box_big", (content_w, board_h)) + if outer_box: + self._photo_refs.append(outer_box) + self.create_image(w // 2, board_cy, image=outer_box, anchor="center", tags="fg") + + sub_ph = self.ctx.assets.get_goth_text_photo( + self._board_heading, + size_px=FONT_SIZE_HEADING - 3, + color=FONT_COLOR_HEADING_SUB, + max_width=content_w - 56, + align="left", + ) + self._photo_refs.append(sub_ph) + self.create_image(left_x + 28, cur_y + 30, image=sub_ph, anchor="w", tags="fg") + + grid_top = cur_y + 58 + grid_h = board_h - 78 + cols, rows = 4, 2 + gap_x, gap_y = 14, 12 + cell_w = (content_w - 56 - (cols - 1) * gap_x) // cols + cell_h = max(68, (grid_h - (rows - 1) * gap_y) // rows) + + cell_frame = self.ctx.assets.get_box_photo("box_purple", (cell_w, cell_h)) + if cell_frame: + self._photo_refs.append(cell_frame) + + for idx, (field_key, label_i18n_key) in enumerate(STAT_FIELD_KEYS): + r, c = divmod(idx, cols) + cx = left_x + 28 + c * (cell_w + gap_x) + cell_w // 2 + cy = grid_top + r * (cell_h + gap_y) + cell_h // 2 + + if cell_frame: + self.create_image(cx, cy, image=cell_frame, anchor="center", tags="fg") + + lbl_ph = self.ctx.assets.get_goth_text_photo( + t(label_i18n_key), + FONT_SIZE_SMALL_MIN, + FONT_COLOR_BODY_MUTED, + max_width=cell_w - 24, + align="center", + ) + if field_key == "won": + v_col = FONT_COLOR_STATUS_WIN + elif field_key == "lost": + v_col = FONT_COLOR_STATUS_LOSS + elif "streak" in field_key or field_key == "win_pct": + v_col = FONT_COLOR_HEADING_SUB + else: + v_col = FONT_COLOR_BODY_DEFAULT + + val_ph = self.ctx.assets.get_goth_text_photo( + str(self._stats_data.get(field_key, "--")), + FONT_SIZE_HEADING - 2, + v_col, + max_width=cell_w - 24, + align="center", + ) + self._photo_refs.extend([lbl_ph, val_ph]) + self.create_image( + cx, cy - cell_h // 4 + 2, image=lbl_ph, anchor="center", tags="fg" + ) + self.create_image( + cx, cy + cell_h // 5 + 2, image=val_ph, anchor="center", tags="fg" + ) \ No newline at end of file diff --git a/view/widgets/__pycache__/image_button.cpython-311.pyc b/view/widgets/__pycache__/image_button.cpython-311.pyc index 60ae77e..e6fc317 100644 Binary files a/view/widgets/__pycache__/image_button.cpython-311.pyc and b/view/widgets/__pycache__/image_button.cpython-311.pyc differ diff --git a/view/widgets/__pycache__/resizing_bg.cpython-311.pyc b/view/widgets/__pycache__/resizing_bg.cpython-311.pyc index 4d11f3e..9c04a45 100644 Binary files a/view/widgets/__pycache__/resizing_bg.cpython-311.pyc and b/view/widgets/__pycache__/resizing_bg.cpython-311.pyc differ diff --git a/view/widgets/goth_switch.py b/view/widgets/goth_switch.py new file mode 100644 index 0000000..56b4f91 --- /dev/null +++ b/view/widgets/goth_switch.py @@ -0,0 +1,261 @@ +# -*- coding: utf-8 -*- +# view/widgets/goth_switch.py +from __future__ import annotations + +from pathlib import Path +import tkinter as tk +from PIL import Image, ImageTk + +from resources.code_res.game_constants import BG_COLOR + +_IMAGES_DIR = Path(__file__).resolve().parents[2] / "resources" / "images" + +SWITCH_TRACK_OFF_FILE = "switch_button_off.png" +SWITCH_TRACK_ON_FILE = "switch_button_on.png" +SWITCH_KNOB_OFF_FILE = "switch_button_off_icon.png" +SWITCH_KNOB_ON_FILE = "switch_button_on_icon.png" + +_RAW_SWITCH_PIL: dict[str, Image.Image | None] = {} +_SCALED_PAIR_CACHE: dict[tuple[str, int, int], Image.Image] = {} + + +def _load_switch_pil(filename: str) -> Image.Image | None: + if filename not in _RAW_SWITCH_PIL: + p = _IMAGES_DIR / filename + if p.is_file(): + try: + _RAW_SWITCH_PIL[filename] = Image.open(p).convert("RGBA") + except Exception: + _RAW_SWITCH_PIL[filename] = None + else: + _RAW_SWITCH_PIL[filename] = None + return _RAW_SWITCH_PIL[filename] + + +def _get_scaled_pil(filename: str, w: int, h: int) -> Image.Image | None: + key = (filename, w, h) + if key in _SCALED_PAIR_CACHE: + return _SCALED_PAIR_CACHE[key] + raw = _load_switch_pil(filename) + if raw is None: + return None + scaled = raw.resize((max(8, w), max(8, h)), Image.Resampling.LANCZOS) + _SCALED_PAIR_CACHE[key] = scaled + return scaled + + +class GothSwitch(tk.Canvas): + """ + Animierter Gothic Toggle-Switch auf Basis von: + - switch_button_off.png / switch_button_on.png (Leiste) + - switch_button_off_icon.png / switch_button_on_icon.png (runder Schieber) + Unterstützt weiches Cubic-Ease-Out-Gleiten + Alpha-Crossfade beim Umschalten. + """ + + ANIM_STEPS = 8 + ANIM_FRAME_MS = 16 + + def __init__( + self, + parent, + value: bool = True, + on_change=None, + sound_mgr=None, + width: int = 92, + height: int = 40, + bg_photo: ImageTk.PhotoImage | None = None, + ): + try: + parent_bg = parent.cget("bg") + except Exception: + parent_bg = BG_COLOR + + # WICHTIG: Nicht self._w nennen, da tk.BaseWidget self._w für den Tcl-Widgetpfad reserviert! + sw_w = max(64, int(width)) + sw_h = max(28, int(height)) + + super().__init__( + parent, + width=sw_w, + height=sw_h, + bg=parent_bg, + bd=0, + highlightthickness=0, + cursor="hand2", + ) + self._sw_w = sw_w + self._sw_h = sw_h + self._value = bool(value) + self._progress: float = 1.0 if self._value else 0.0 + self._on_change = on_change + self._sound_mgr = sound_mgr + self._anim_job: str | None = None + self._bg_photo = bg_photo + + self._frame_photo: ImageTk.PhotoImage | None = None + self._prepare_geometry() + self._render_progress(self._progress) + + self.bind("", self._on_click) + self.bind("", self._on_destroy) + + @property + def value(self) -> bool: + return self._value + + def set_bg_photo(self, bg_photo: ImageTk.PhotoImage | None): + """Optionaler Hintergrund-Ausschnitt für nahtlose Transparenz auf Texturen.""" + self._bg_photo = bg_photo + self._render_progress(self._progress) + + def set_value(self, new_val: bool, animate: bool = False, notify: bool = False): + new_val = bool(new_val) + if new_val == self._value and not animate: + return + self._value = new_val + target = 1.0 if self._value else 0.0 + if animate and self.winfo_exists(): + self._start_animation(target) + else: + self._cancel_anim() + self._progress = target + self._render_progress(self._progress) + if notify and callable(self._on_change): + self._on_change(self._value) + + def toggle(self): + if self._sound_mgr is not None: + self._sound_mgr.play("click") + self.set_value(not self._value, animate=True, notify=True) + + def _on_click(self, event): + if 0 <= event.x <= self._sw_w and 0 <= event.y <= self._sw_h: + self.toggle() + + def _on_destroy(self, event=None): + if event is not None and event.widget is not self: + return + self._cancel_anim() + + def _cancel_anim(self): + if self._anim_job is not None: + try: + self.after_cancel(self._anim_job) + except Exception: + pass + self._anim_job = None + + def _prepare_geometry(self): + raw_track = _load_switch_pil(SWITCH_TRACK_OFF_FILE) + raw_knob = _load_switch_pil(SWITCH_KNOB_OFF_FILE) + + if raw_track is not None: + tw_src, th_src = raw_track.size + aspect = tw_src / max(1, th_src) + track_h = self._sw_h + track_w = min(self._sw_w, int(round(track_h * aspect))) + if track_w < self._sw_w - 4: + track_w = self._sw_w + track_h = max(24, min(self._sw_h, int(round(track_w / max(0.5, aspect))))) + else: + track_w, track_h = self._sw_w, self._sw_h + + self._track_size = (track_w, track_h) + self._track_xy = ((self._sw_w - track_w) // 2, (self._sw_h - track_h) // 2) + + knob_d = max(22, int(round(track_h * 0.86))) + if raw_knob is not None and raw_knob.height > 0: + k_aspect = raw_knob.width / raw_knob.height + knob_w = int(round(knob_d * k_aspect)) + else: + knob_w = knob_d + self._knob_size = (knob_w, knob_d) + + t_scaled = _get_scaled_pil(SWITCH_TRACK_OFF_FILE, track_w, track_h) + bbox = t_scaled.getbbox() if t_scaled is not None else None + if bbox is not None: + vis_left = self._track_xy[0] + bbox[0] + vis_right = self._track_xy[0] + bbox[2] + else: + vis_left = self._track_xy[0] + vis_right = self._track_xy[0] + track_w + + edge_pad = max(3, int(round(track_w * 0.055))) + self._knob_x_off = vis_left + edge_pad + self._knob_x_on = max(self._knob_x_off, vis_right - edge_pad - knob_w) + self._knob_y = (self._sw_h - knob_d) // 2 + + def _start_animation(self, target: float): + self._cancel_anim() + start_p = self._progress + diff = target - start_p + if abs(diff) < 0.01: + self._progress = target + self._render_progress(target) + return + + def step(frame_idx: int): + if not self.winfo_exists(): + return + t_norm = min(1.0, frame_idx / float(self.ANIM_STEPS)) + eased = 1.0 - pow(1.0 - t_norm, 3) + self._progress = start_p + diff * eased + self._render_progress(self._progress) + if frame_idx < self.ANIM_STEPS: + self._anim_job = self.after(self.ANIM_FRAME_MS, lambda: step(frame_idx + 1)) + else: + self._progress = target + self._anim_job = None + + step(1) + + def _render_progress(self, p: float): + p = max(0.0, min(1.0, float(p))) + tw, th = self._track_size + kw, kh = self._knob_size + + t_off = _get_scaled_pil(SWITCH_TRACK_OFF_FILE, tw, th) + t_on = _get_scaled_pil(SWITCH_TRACK_ON_FILE, tw, th) + k_off = _get_scaled_pil(SWITCH_KNOB_OFF_FILE, kw, kh) + k_on = _get_scaled_pil(SWITCH_KNOB_ON_FILE, kw, kh) + + self.delete("sw") + + if self._bg_photo is not None: + self.create_image(0, 0, image=self._bg_photo, anchor="nw", tags="sw") + + if t_off is None or t_on is None or k_off is None or k_on is None: + fill_c = "#7030a0" if p >= 0.5 else "#191522" + self.create_oval( + 2, 4, self._sw_h - 2, self._sw_h - 4, fill=fill_c, outline="#5d4b7a", tags="sw" + ) + self.create_oval( + self._sw_w - self._sw_h + 2, 4, self._sw_w - 2, self._sw_h - 4, + fill=fill_c, outline="#5d4b7a", tags="sw", + ) + self.create_rectangle( + self._sw_h // 2, 4, self._sw_w - self._sw_h // 2, self._sw_h - 4, + fill=fill_c, outline="", tags="sw", + ) + kx = int(round(self._knob_x_off + (self._knob_x_on - self._knob_x_off) * p)) + knob_c = "#b266ff" if p >= 0.5 else "#3c354a" + self.create_oval( + kx, self._knob_y, kx + kw, self._knob_y + kh, + fill=knob_c, outline="#d4af37", width=2, tags="sw", + ) + return + + canvas_pil = Image.new("RGBA", (self._sw_w, self._sw_h), (0, 0, 0, 0)) + track_frame = ( + t_off if p <= 0.001 else (t_on if p >= 0.999 else Image.blend(t_off, t_on, p)) + ) + knob_frame = ( + k_off if p <= 0.001 else (k_on if p >= 0.999 else Image.blend(k_off, k_on, p)) + ) + + canvas_pil.alpha_composite(track_frame, dest=self._track_xy) + kx = int(round(self._knob_x_off + (self._knob_x_on - self._knob_x_off) * p)) + canvas_pil.alpha_composite(knob_frame, dest=(kx, self._knob_y)) + + self._frame_photo = ImageTk.PhotoImage(canvas_pil) + self.create_image(0, 0, image=self._frame_photo, anchor="nw", tags="sw") \ No newline at end of file diff --git a/view/widgets/goth_topbar.py b/view/widgets/goth_topbar.py new file mode 100644 index 0000000..17ed76b --- /dev/null +++ b/view/widgets/goth_topbar.py @@ -0,0 +1,421 @@ +# -*- coding: utf-8 -*- +# view/widgets/goth_topbar.py +from __future__ import annotations + +from types import SimpleNamespace +import tkinter as tk +from PIL import Image, ImageTk + +from resources.code_res.game_constants import ( + BG_COLOR, + FONT_COLOR_BODY_DEFAULT, + FONT_COLOR_STATUS_LOSS, + FONT_SIZE_BODY, + FONT_SIZE_SMALL_MIN, +) +from resources.code_res.i18n import t +from view.dialogs.audio_settings_dialog import is_german_active +from view.widgets.image_button import ImageButton + + +def format_compact_user_badge(profile: dict, progress: dict) -> str: + """Nutzername (max. 8 Zeichen), Spiel-Level als Nummer und Spiel-XP.""" + raw_name = str(profile.get("name", "") or "").strip() + short_name = raw_name[:8] + + lvl_num = int(progress.get("level", 1) or 1) + raw_exp = progress.get("total_points", progress.get("current_xp", 0)) + exp_val = min(99_999_999, max(0, int(raw_exp or 0))) + exp_str = str(exp_val)[:8] + + return f"{short_name} Lv. {lvl_num} {exp_str} XP" + + +def _noop_configure(**_kwargs): + pass + + +class GothTopbar(tk.Canvas): + """ + Statische, universelle Kopfleiste für alle Spiele: + - Einmaliges Setup beim Laden der Ansicht: `configure_stats_link(stats_endpoint, on_stats_back)` + - Links: 'Hauptmenü' + 'Statistiken' (öffnet zentral UnifiedStatsView für `stats_endpoint`) + - Rechts: Level/XP-Text (zentriert im rechten Flügel) + 'Einstellungen' + - Zur Laufzeit ändert sich ausschließlich der Level/XP-Text ohne Layout-Redraw! + """ + + # Fein-Offsets für die Position von "Kuro Lv. X Y XP" + BADGE_X_OFFSET = 0 # Negativ = weiter nach links zur Mitte, Positiv = näher an Einstellungen + BADGE_Y_OFFSET = 7 # Gleiche optische Zeilenhöhe wie die Button-Beschriftung + + def __init__( + self, + parent, + ctx, + stats_endpoint: str | None = None, + on_stats_back=None, + badge_text: str | None = None, + stats_enabled: bool = True, + on_lang_refresh=None, + locked_exit: bool = False, + on_main_menu=None, + # Optionale Alt-Parameter zur Abwärtskompatibilität bestehender Spiele: + title: str = "", + on_game_menu=None, + on_stats=None, + extra_right_text: str = "", + ): + del title, on_game_menu, on_stats, extra_right_text + self._root_win = parent.winfo_toplevel() + root_h = max(680, self._root_win.winfo_height()) + self._bar_h = max(68, int(root_h * 0.098)) + + super().__init__( + parent, + height=self._bar_h, + bg=BG_COLOR, + bd=0, + highlightthickness=0, + ) + self.ctx = ctx + self.assets = ctx.assets + self.sounds = ctx.sounds + self._locked_exit = bool(locked_exit) + self._on_main_menu = on_main_menu or ctx.back_to_main_menu + self._stats_enabled = bool(stats_enabled) + self._on_lang_refresh = on_lang_refresh + + self._stats_endpoint: str | None = ( + stats_endpoint if stats_endpoint is not None else getattr(ctx, "game_folder", None) + ) + self._on_stats_back = on_stats_back + + self._bg_slice_photo: ImageTk.PhotoImage | None = None + self._lock_photo: ImageTk.PhotoImage | None = None + self._badge_photo: ImageTk.PhotoImage | None = None + self._badge_item_id: int | None = None + self._badge_anchor_xy: tuple[int, int] = (0, 0) + self._badge_max_w: int = 260 + + self._badge_color: str = FONT_COLOR_BODY_DEFAULT + self._badge_size_px: int = FONT_SIZE_SMALL_MIN + 1 + self._badge_custom_override: str | None = badge_text + self._badge_text: str = "" + self._refresh_badge_text_from_db() + + self._last_render_key: tuple[int, int, int, int, int, int] = (0, 0, 0, 0, 0, 0) + self._sync_job: str | None = None + self._root_cfg_bind_id: str | None = None + + self._left_widgets: list[tuple[ImageButton, int]] = [] + self._right_widgets: list[tuple[ImageButton, int]] = [] + self.stats_btn: ImageButton | None = None + + # Klassenlose Namespace-Adapter für volle Abwärtskompatibilität zu bestehenden Views + self.title_label = SimpleNamespace(text="", configure=_noop_configure, config=_noop_configure) + self.extra_label = SimpleNamespace(text="", configure=_noop_configure, config=_noop_configure) + self.level_label = SimpleNamespace( + text=self._badge_text, + configure=self._configure_level_slot, + config=self._configure_level_slot, + refresh_from_db=self.update_level_xp_text, + set_text=self.update_level_xp_text, + ) + + self._build_static_buttons() + + self.bind("", self._on_configure) + self.bind("", self._on_destroy) + try: + self._root_cfg_bind_id = self._root_win.bind( + "", self._on_root_configure, add="+" + ) + except tk.TclError: + self._root_cfg_bind_id = None + + self.after(10, self._sync_bg_and_layout) + + @property + def total_height(self) -> int: + return self._bar_h + + def _refresh_badge_text_from_db(self): + if self._badge_custom_override is not None: + self._badge_text = self._badge_custom_override + else: + prof = self.ctx.profile or {} + prog = self.ctx.refresh_game_progress() if prof else {} + self._badge_text = format_compact_user_badge(prof, prog) if prof else "" + if hasattr(self, "level_label"): + self.level_label.text = self._badge_text + + def _configure_level_slot(self, **kwargs): + prev_txt, prev_col = self._badge_text, self._badge_color + if "fg" in kwargs and kwargs["fg"] != self._badge_color: + self._badge_color = kwargs["fg"] + if "text" in kwargs: + self._badge_custom_override = None + self._refresh_badge_text_from_db() + if self._badge_text != prev_txt or self._badge_color != prev_col: + self._update_badge_item_only() + + def configure_stats_link(self, game_endpoint: str | None, on_back_view=None): + """Stellt beim Laden einer Ansicht einmalig den Statistik-Endpunkt ein – ohne Redraw!""" + self._stats_endpoint = game_endpoint + self._on_stats_back = on_back_view + if self.stats_btn is not None and self.stats_btn.winfo_exists(): + self.stats_btn.set_enabled(bool(self._stats_enabled)) + + def update_level_xp_text(self, text: str | None = None): + """Aktualisiert ausschließlich den Level/XP-Text rechts oben ohne Layout-Redraw.""" + prev = self._badge_text + self._badge_custom_override = text + self._refresh_badge_text_from_db() + if self._badge_text != prev: + self._update_badge_item_only() + + set_badge_text = update_level_xp_text + + def set_locked_exit(self, locked: bool): + locked = bool(locked) + if locked == self._locked_exit: + return + self._locked_exit = locked + self._build_static_buttons() + self._last_render_key = (0, 0, 0, 0, 0, 0) + self._sync_bg_and_layout() + + def _trigger_central_stats(self): + if self._locked_exit or not self._stats_enabled: + return + from view.unified_stats_view import UnifiedStatsView + + UnifiedStatsView.open( + self.ctx, + game_endpoint=self._stats_endpoint, + on_back=self._on_stats_back, + ) + + def _build_static_buttons(self): + for wgt, _bw in self._left_widgets + self._right_widgets: + try: + if wgt.winfo_exists(): + wgt.place_forget() + wgt.destroy() + except Exception: + pass + self._left_widgets.clear() + self._right_widgets.clear() + self.stats_btn = None + + btn_norm = self.assets.raw_btn_default + btn_purp = self.assets.raw_btn_purple + + if not self._locked_exit: + b_main = ImageButton( + self, + t("btn_back_main"), + btn_norm, + btn_purp, + self._on_main_menu, + sound_mgr=self.sounds, + width=112, + height=32, + style="amethyst", + ) + self._left_widgets.append((b_main, b_main.pixel_width)) + + if self._stats_enabled: + self.stats_btn = ImageButton( + self, + t("btn_stats"), + btn_norm, + btn_purp, + self._trigger_central_stats, + sound_mgr=self.sounds, + width=102, + height=32, + enabled=True, + style="amethyst", + ) + self._left_widgets.append((self.stats_btn, self.stats_btn.pixel_width)) + + settings_lbl = "Einstellungen" if is_german_active() else "Settings" + b_settings = ImageButton( + self, + settings_lbl, + btn_norm, + btn_purp, + lambda: self.ctx.open_settings(on_lang_refresh=self._on_lang_refresh), + sound_mgr=self.sounds, + width=122, + height=32, + style="amethyst", + ) + self._right_widgets.append((b_settings, b_settings.pixel_width)) + + def _on_destroy(self, event=None): + if event is not None and event.widget is not self: + return + if self._sync_job is not None: + try: + self.after_cancel(self._sync_job) + except Exception: + pass + self._sync_job = None + if self._root_cfg_bind_id is not None: + try: + self._root_win.unbind("", self._root_cfg_bind_id) + except Exception: + pass + self._root_cfg_bind_id = None + + def _on_root_configure(self, event=None): + if event is not None and event.widget is not self._root_win: + return + self._schedule_sync() + + def _on_configure(self, event): + if event.widget is not self or event.width < 100: + return + self._schedule_sync() + + def _schedule_sync(self): + if not self.winfo_exists(): + return + if self._sync_job is not None: + try: + self.after_cancel(self._sync_job) + except Exception: + pass + self._sync_job = self.after(18, self._sync_bg_and_layout) + + def _sync_bg_and_layout(self): + self._sync_job = None + if not self.winfo_exists(): + return + + rw = max(1, self._root_win.winfo_width()) + rh = max(600, self._root_win.winfo_height()) + w = max(1, self.winfo_width()) + if w < 100 or rw < 100: + return + + target_h = max(68, int(rh * 0.098)) + if target_h != self._bar_h: + self._bar_h = target_h + self.configure(height=target_h) + + ox = max(0, min(max(0, rw - w), self.winfo_rootx() - self._root_win.winfo_rootx())) + oy = max(0, min(max(0, rh - target_h), self.winfo_rooty() - self._root_win.winfo_rooty())) + + render_key = (w, target_h, rw, rh, ox, oy) + tk.Widget.tkraise(self) + if render_key == self._last_render_key: + return + self._last_render_key = render_key + + self._render_bg_slice(w, target_h, rw, rh, ox, oy) + self._layout_static_items(w, target_h, rh) + + def _render_bg_slice( + self, w: int, bar_h: int, rw: int, rh: int, ox: int, oy: int + ): + slice_w = min(w, rw - ox) + slice_h = min(bar_h, rh - oy) + if slice_w < 40 or slice_h < 20: + return + + if hasattr(self.assets, "get_bg_patch_photo"): + self._bg_slice_photo = self.assets.get_bg_patch_photo( + rw, rh, ox, oy, slice_w, slice_h + ) + else: + src = ( + self.assets.raw_bg_vertical + if (rh > rw and self.assets.raw_bg_vertical is not None) + else (self.assets.raw_bg_horizontal or self.assets.raw_bg) + ) + if src is None: + return + full_scaled = src.resize((rw, rh), Image.Resampling.BILINEAR) + self._bg_slice_photo = ImageTk.PhotoImage( + full_scaled.crop((ox, oy, ox + slice_w, oy + slice_h)) + ) + + if self._bg_slice_photo is None: + return + self.delete("topbar_bg") + self.create_image(0, 0, image=self._bg_slice_photo, anchor="nw", tags="topbar_bg") + self.tag_lower("topbar_bg") + + def _layout_static_items(self, w: int, bar_h: int, root_h: int): + self.delete("topbar_lock") + pad_x = max(96, int(w * 0.095)) + btn_cy = min(bar_h - 18, max(42, int(root_h * 0.066))) + + left_x = pad_x + if self._locked_exit: + self._lock_photo = self.assets.get_goth_text_photo( + t("devils_deal_locked_badge"), + size_px=FONT_SIZE_BODY, + color=FONT_COLOR_STATUS_LOSS, + align="left", + ) + self.create_image( + left_x, btn_cy, image=self._lock_photo, anchor="w", tags="topbar_lock" + ) + left_x += self._lock_photo.width() + 10 + else: + for wgt, bw in self._left_widgets: + bh = wgt.pixel_height + wgt.place(x=left_x, y=btn_cy - bh // 2, width=bw, height=bh) + tk.Widget.tkraise(wgt) + left_x += bw + 8 + + right_x = w - pad_x + for wgt, bw in reversed(self._right_widgets): + bh = wgt.pixel_height + wgt.place(x=right_x - bw, y=btn_cy - bh // 2, width=bw, height=bh) + tk.Widget.tkraise(wgt) + right_x -= (bw + 8) + + # Zentriert den Spieler-Badge mittig im rechten Flügel zwischen Mittelornament (~55% w) und Einstellungen + right_wing_start = max(left_x + 24, int(w * 0.555)) + if right_x > right_wing_start + 80: + badge_cx = (right_wing_start + right_x) // 2 + self.BADGE_X_OFFSET + self._badge_max_w = max(120, right_x - right_wing_start - 16) + else: + badge_cx = (left_x + right_x) // 2 + self.BADGE_X_OFFSET + self._badge_max_w = max(120, right_x - left_x - 20) + + self._badge_anchor_xy = (badge_cx, btn_cy + self.BADGE_Y_OFFSET) + self._update_badge_item_only() + + def _update_badge_item_only(self): + if not self.winfo_exists(): + return + bx, by = self._badge_anchor_xy + if bx <= 0 or not self._badge_text: + if self._badge_item_id is not None: + self.delete(self._badge_item_id) + self._badge_item_id = None + return + + self._badge_photo = self.assets.get_goth_text_photo( + self._badge_text, + size_px=self._badge_size_px, + color=self._badge_color, + max_width=self._badge_max_w, + align="center", + ) + if self._badge_item_id is not None and self.type(self._badge_item_id): + self.itemconfigure(self._badge_item_id, image=self._badge_photo, anchor="center") + self.coords(self._badge_item_id, bx, by) + else: + self._badge_item_id = self.create_image( + bx, by, image=self._badge_photo, anchor="center", tags="topbar_badge" + ) + + def refresh_text_slots(self): + self._update_badge_item_only() \ No newline at end of file diff --git a/view/widgets/image_button.py b/view/widgets/image_button.py index 0d3099c..75e3af9 100644 --- a/view/widgets/image_button.py +++ b/view/widgets/image_button.py @@ -5,9 +5,12 @@ from __future__ import annotations import re from pathlib import Path import tkinter as tk -from PIL import Image, ImageDraw, ImageEnhance, ImageFont, ImageTk, ImageChops +from typing import Callable +from PIL import Image, ImageChops, ImageDraw, ImageEnhance, ImageFont, ImageTk +from models.database import Database from resources.code_res.game_constants import ( + ACCENT_GOTH, BG_COLOR, BTN_AMETHYST_TEXT_ACTIVE, BTN_AMETHYST_TEXT_DISABLED, @@ -17,6 +20,7 @@ from resources.code_res.game_constants import ( BTN_FIRE_TEXT_DISABLED, BTN_FIRE_TEXT_HOVER, BTN_FIRE_TEXT_NORMAL, + FG_COLOR, FONTS_REL_DIR, FONT_FILE_PRIMARY, FONT_FORCE_MIXED_CASE, @@ -29,21 +33,51 @@ from resources.code_res.game_constants import ( FONT_SIZE_BUTTON, FONT_SIZE_SMALL_MIN, FONT_VERTICAL_OFFSET_PX, + MODAL_BG, ) +SETTING_BUTTON_HOVER_HELP = "show_button_hover_help" + _ROOT_DIR = Path(__file__).resolve().parents[2] _FONT_CACHE: dict[int, ImageFont.FreeTypeFont | ImageFont.ImageFont] = {} _ALPHA_CORNER_CACHE: dict[tuple[int, int, int], Image.Image] = {} _TRIM_BTN_CACHE: dict[tuple[int, int, int], Image.Image] = {} _BTN_PHOTO_CACHE: dict[tuple, ImageTk.PhotoImage] = {} -# Entfernt alle vorangestellten/nachgestellten Sonder-Icons & Emojis (behält Buchstaben, Ziffern, '+' vor Zahl & Klammern) +_HOVER_HELP_ENABLED_CACHE: bool | None = None + +# Entfernt vorangestellte/nachgestellte Sonder-Icons & Emojis (behält Buchstaben, Ziffern, '+' vor Zahl & Klammern) _LEADING_ICON_RE = re.compile(r"^(?:[^\w\s\+\(\[\"'ÄÖÜäöüß]+|\+(?=\s))\s*", re.UNICODE) _TRAILING_ICON_RE = re.compile(r"\s*[^\w\s\)\]\.\!\%\"'ÄÖÜäöüß]+$", re.UNICODE) # Geometrie-Anteil der seitlichen Zierkappen & oberen/unteren Rahmenleisten in button*.png -_SIDE_CAP_ASPECT = 0.46 # Breite einer Seitenkappe relativ zur Button-Höhe (inkl. Innenspitze) -_VERTICAL_FRAME_RATIO = 0.36 # Anteil oben + unten für Metallrahmen & Mittel-Ornament +_SIDE_CAP_ASPECT = 0.46 +_VERTICAL_FRAME_RATIO = 0.36 + + +def is_button_hover_help_enabled() -> bool: + """Liest den globalen Einstellungs-Schalter für Button-Hover-Hilfetexte (gecached).""" + global _HOVER_HELP_ENABLED_CACHE + if _HOVER_HELP_ENABLED_CACHE is None: + try: + raw = Database.load_setting(SETTING_BUTTON_HOVER_HELP, default="1") + _HOVER_HELP_ENABLED_CACHE = str(raw).strip() not in ("0", "false", "False", "off") + except Exception: + _HOVER_HELP_ENABLED_CACHE = True + return _HOVER_HELP_ENABLED_CACHE + + +def set_button_hover_help_enabled(enabled: bool, persist: bool = True): + """Aktualisiert den Einstellungsschalter zur Laufzeit und schließt ggf. offene Popups.""" + global _HOVER_HELP_ENABLED_CACHE + _HOVER_HELP_ENABLED_CACHE = bool(enabled) + if not _HOVER_HELP_ENABLED_CACHE: + ImageButton.close_active_hover_tip() + if persist: + try: + Database.save_setting(SETTING_BUTTON_HOVER_HELP, "1" if _HOVER_HELP_ENABLED_CACHE else "0") + except Exception: + pass def _get_old_london(size_px: int) -> ImageFont.FreeTypeFont | ImageFont.ImageFont: @@ -58,10 +92,6 @@ def _get_old_london(size_px: int) -> ImageFont.FreeTypeFont | ImageFont.ImageFon def _clean_outer_black_matte(pil_img: Image.Image) -> Image.Image: - """ - Entfernt schwarze JPEG-Außenränder in C-Geschwindigkeit über ImageDraw.floodfill - statt langsamer Python-Pixel-Stacks. - """ key = (id(pil_img), pil_img.width, pil_img.height) if key in _ALPHA_CORNER_CACHE: return _ALPHA_CORNER_CACHE[key] @@ -70,17 +100,13 @@ def _clean_outer_black_matte(pil_img: Image.Image) -> Image.Image: w, h = rgba.size tl = rgba.getpixel((0, 0)) - # Nur ausführen, wenn das Bild überhaupt einen opaken schwarzen Rand hat (z. B. .jpg) if tl[3] > 240 and max(tl[:3]) < 16: - # Helligkeitsmaske in C berechnen: alles < 18 wird 0, Rest 255 r, g, b, a = rgba.split() luma = ImageChops.lighter(ImageChops.lighter(r, g), b) - # Floodfill vom Rand auf Kopie markiert zusammenhängendes Außenschwarz mit Wert 128 seed_img = luma.point(lambda p: 0 if p < 18 else 255) for seed in ((0, 0), (w - 1, 0), (0, h - 1), (w - 1, h - 1)): if seed_img.getpixel(seed) == 0: ImageDraw.floodfill(seed_img, seed, 128) - # Überall wo 128 steht -> Alpha = 0, sonst Original-Alpha behalten ext_alpha = seed_img.point(lambda p: 0 if p == 128 else 255) rgba.putalpha(ImageChops.darker(a, ext_alpha)) @@ -89,7 +115,6 @@ def _clean_outer_black_matte(pil_img: Image.Image) -> Image.Image: def _trim_button_art(pil_img: Image.Image) -> Image.Image: - """Entfernt leere transparente/schwarze Außenränder um die eigentliche Button-Grafik.""" key = (id(pil_img), pil_img.width, pil_img.height) if key in _TRIM_BTN_CACHE: return _TRIM_BTN_CACHE[key] @@ -102,12 +127,6 @@ def _trim_button_art(pil_img: Image.Image) -> Image.Image: def _scale_button_3slice(src_pil: Image.Image, target_w: int, target_h: int) -> tuple[Image.Image, int]: - """ - Skaliert die Button-Grafik verzerrungsfrei per 3-Slice: - - Linke & rechte Zierkappe skalieren proportional zur Zielhöhe (keine plattgezogenen Spitzen!). - - Das Mittelstück (Damast + Mittel-Ornament) übernimmt die restliche Breite. - Gibt (fertiges RGBA-Bild, effektive Seitenkappen-Breite in px) zurück. - """ trimmed = _trim_button_art(src_pil) sw, sh = trimmed.size @@ -131,11 +150,14 @@ def _scale_button_3slice(src_pil: Image.Image, target_w: int, target_h: int) -> class ImageButton(tk.Label): """ - Gothic UI Button (Amethyst & Fire) mit echter Rahmen-Einberechnung: - Berechnet Seitenkappen + oberen/unteren Zierrahmen automatisch in die Button-Größe ein, - sodass Text niemals in die Eck-Spitzen oder Rahmenlinien ragt. + Gothic UI Button (Amethyst & Fire) mit automatischer Rahmen-Einberechnung + und optionalem Hover-Hilfetext (`hover_text`) in klar lesbarer Standard-Schrift, + steuerbar über die Einstellungen ('Hilfe Texte bei Buttons Anzeigen'). """ + _active_tip: tk.Toplevel | None = None + _active_tip_owner: "ImageButton | None" = None + def __init__( self, parent, @@ -150,6 +172,7 @@ class ImageButton(tk.Label): enabled: bool = True, style: str | None = None, auto_expand: bool = True, + hover_text: str | Callable[[], str] | None = None, ): try: parent_bg = parent.cget("bg") @@ -166,6 +189,8 @@ class ImageButton(tk.Label): self._user_cmd = command self._enabled = bool(enabled) self._hovered = False + self._hover_text = hover_text + self._hover_after_id: str | None = None if style in ("fire", "amethyst"): self._style = style @@ -176,7 +201,7 @@ class ImageButton(tk.Label): self._width = self._compute_framed_width() self._rebuild_state_photos() - init_photo = self._photo_normal if self._enabled else self._photo_disabled + init_photo = self._ensure_normal() if self._enabled else self._ensure_disabled() super().__init__( parent, @@ -194,16 +219,108 @@ class ImageButton(tk.Label): self.bind("", self._on_leave) self.bind("", self._on_press) self.bind("", self._on_release) + self.bind("", self._on_destroy) @property def pixel_width(self) -> int: - """Tatsächliche Gesamtbreite des Buttons inklusive Rahmen-Aufschlag.""" return self._width @property def pixel_height(self) -> int: return self._height + def set_hover_text(self, hover_text: str | Callable[[], str] | None): + self._hover_text = hover_text + if not hover_text and ImageButton._active_tip_owner is self: + ImageButton.close_active_hover_tip() + + @classmethod + def close_active_hover_tip(cls): + if cls._active_tip is not None: + try: + if cls._active_tip.winfo_exists(): + cls._active_tip.destroy() + except Exception: + pass + cls._active_tip = None + cls._active_tip_owner = None + + def _cancel_hover_timer(self): + if self._hover_after_id is not None: + try: + self.after_cancel(self._hover_after_id) + except Exception: + pass + self._hover_after_id = None + + def _resolve_hover_string(self) -> str: + if self._hover_text is None: + return "" + try: + raw = self._hover_text() if callable(self._hover_text) else str(self._hover_text) + return (raw or "").strip() + except Exception: + return "" + + def _show_hover_tooltip(self): + self._hover_after_id = None + if not self._hovered or not self.winfo_exists(): + return + if not is_button_hover_help_enabled(): + return + + msg = self._resolve_hover_string() + if not msg: + return + + ImageButton.close_active_hover_tip() + + tip = tk.Toplevel(self) + tip.wm_overrideredirect(True) + try: + tip.wm_attributes("-topmost", True) + except Exception: + pass + + border_frame = tk.Frame(tip, bg=ACCENT_GOTH, padx=1, pady=1) + border_frame.pack(fill="both", expand=True) + + inner_frame = tk.Frame(border_frame, bg=MODAL_BG, padx=12, pady=8) + inner_frame.pack(fill="both", expand=True) + + # Gut lesbare Standard-Schrift (wie in InfoBadge) statt Gothic/Serifenschrift + lbl = tk.Label( + inner_frame, + text=msg, + font=("Helvetica", 9), + fg=FG_COLOR, + bg=MODAL_BG, + justify="left", + wraplength=340, + ) + lbl.pack() + + tip.update_idletasks() + tw = tip.winfo_reqwidth() + th = tip.winfo_reqheight() + sw = self.winfo_screenwidth() + sh = self.winfo_screenheight() + + bx = self.winfo_rootx() + by = self.winfo_rooty() + + rx = bx + (self._width - tw) // 2 + ry = by - th - 10 + if ry < 14: + ry = by + self._height + 10 + + rx = max(12, min(sw - tw - 12, rx)) + ry = max(12, min(sh - th - 16, ry)) + + tip.wm_geometry(f"+{rx}+{ry}") + ImageButton._active_tip = tip + ImageButton._active_tip_owner = self + @staticmethod def _measure_text_px(text: str, pil_font) -> float: if not text: @@ -218,12 +335,10 @@ class ImageButton(tk.Label): return total def _horizontal_frame_inset(self) -> int: - """Breite EINER seitlichen Rahmenkappe + Sicherheitsabstand vor der Innenspitze.""" cap_px = max(13, int(round(self._height * _SIDE_CAP_ASPECT))) return cap_px + 6 def _compute_framed_width(self) -> int: - """Stellt sicher, dass width immer groß genug für Text + beide Seitenrahmen ist.""" if not self._text or not self._auto_expand: return self._requested_width pil_font = _get_old_london(self._font_px) @@ -262,7 +377,6 @@ class ImageButton(tk.Label): @staticmethod def _resolve_font_px(font_arg, btn_h: int) -> int: - # Nur das innere Feld abzüglich oberem/unterem Zierrahmen (_VERTICAL_FRAME_RATIO) für die Schrift nutzen! inner_h = max(14.0, btn_h * (1.0 - _VERTICAL_FRAME_RATIO)) max_safe_px = max(14, min(FONT_SIZE_BUTTON, int(round(inner_h * 0.80)))) auto_px = max(FONT_SIZE_SMALL_MIN if btn_h >= 34 else 14, max_safe_px) @@ -386,7 +500,6 @@ class ImageButton(tk.Label): def _rebuild_state_photos(self): c_norm, _c_hov, _c_act, c_dis = self._palette() - # Lazy Rendering: Nur den initial sichtbaren Zustand sofort berechnen! self._photo_normal = self._compose_button_photo(self._pil_normal, c_norm) if self._enabled else None self._photo_disabled = None if self._enabled else self._compose_button_photo(self._pil_normal, c_dis, dim_disabled=True) self._photo_hover = None @@ -416,10 +529,19 @@ class ImageButton(tk.Label): self._photo_disabled = self._compose_button_photo(self._pil_normal, c_dis, dim_disabled=True) return self._photo_disabled + def set_text(self, new_text: str): + self._text = self._prepare_label_text(str(new_text or "")) + self._width = self._compute_framed_width() + self._rebuild_state_photos() + self.set_enabled(self._enabled) + def set_enabled(self, enabled: bool): self._enabled = bool(enabled) if not self._enabled: self._hovered = False + self._cancel_hover_timer() + if ImageButton._active_tip_owner is self: + ImageButton.close_active_hover_tip() ph = self._ensure_disabled() self.configure(image=ph if ph else "", cursor="arrow") else: @@ -427,15 +549,20 @@ class ImageButton(tk.Label): self.configure(image=ph if ph else "", cursor="hand2") def _on_enter(self, _event): - if not self._enabled: - return self._hovered = True - ph = self._ensure_hover() - if ph: - self.configure(image=ph) + if self._enabled: + ph = self._ensure_hover() + if ph: + self.configure(image=ph) + if self._hover_text is not None and is_button_hover_help_enabled(): + self._cancel_hover_timer() + self._hover_after_id = self.after(220, self._show_hover_tooltip) def _on_leave(self, _event): self._hovered = False + self._cancel_hover_timer() + if ImageButton._active_tip_owner is self: + ImageButton.close_active_hover_tip() if not self._enabled: return ph = self._ensure_normal() @@ -443,6 +570,9 @@ class ImageButton(tk.Label): self.configure(image=ph) def _on_press(self, _event): + self._cancel_hover_timer() + if ImageButton._active_tip_owner is self: + ImageButton.close_active_hover_tip() if not self._enabled: return ph = self._ensure_active() @@ -463,64 +593,9 @@ class ImageButton(tk.Label): if self._user_cmd: self._user_cmd() - def _rebuild_state_photos(self): - c_norm, c_hov, c_act, c_dis = self._palette() - self._photo_normal = self._compose_button_photo(self._pil_normal, c_norm) - self._photo_hover = self._compose_button_photo(self._pil_hover, c_hov) - self._photo_active = self._compose_button_photo(self._pil_hover, c_act, brighten_active=True) - self._photo_disabled = self._compose_button_photo(self._pil_normal, c_dis, dim_disabled=True) - - def set_text(self, new_text: str): - self._text = self._prepare_label_text(str(new_text or "")) - self._width = self._compute_framed_width() - self._rebuild_state_photos() - self.set_enabled(self._enabled) - - def set_enabled(self, enabled: bool): - self._enabled = bool(enabled) - if not self._enabled: - self._hovered = False - self.configure( - image=self._photo_disabled if self._photo_disabled else "", - cursor="arrow", - ) - else: - target = self._photo_hover if self._hovered else self._photo_normal - self.configure( - image=target if target else "", - cursor="hand2", - ) - - def _on_enter(self, _event): - if not self._enabled: + def _on_destroy(self, event=None): + if event is not None and event.widget is not self: return - self._hovered = True - if self._photo_hover: - self.configure(image=self._photo_hover) - - def _on_leave(self, _event): - self._hovered = False - if not self._enabled: - return - if self._photo_normal: - self.configure(image=self._photo_normal) - - def _on_press(self, _event): - if not self._enabled: - return - if self._photo_active: - self.configure(image=self._photo_active) - - def _on_release(self, event): - if not self._enabled: - return - inside = (0 <= event.x < self._width) and (0 <= event.y < self._height) - self._hovered = inside - target = self._photo_hover if inside else self._photo_normal - if target: - self.configure(image=target) - if inside: - if self._sound_mgr: - self._sound_mgr.play("click") - if self._user_cmd: - self._user_cmd() \ No newline at end of file + self._cancel_hover_timer() + if ImageButton._active_tip_owner is self: + ImageButton.close_active_hover_tip() \ No newline at end of file