feat(ui): Top-/Bottom-Bar zentralisieren, Poker & Blackjack überarbeiten & 1-Klasse-pro-Datei durchsetzen

- GothTopbar ausgelagert & entschlackt (ohne Spieltitel/Spielmenü-Button, Sprachwechsel in kombinierten Einstellungs-Dialog verschoben, zentriertes Level/XP-Badge)
- SolitaireBottomBar um dynamische Links-/Rechts-Overflow-Flügel, Pipe-Trenner, zentriertes HUD und sauberes Button-Cleanup erweitert
- Zentrale Vollbild-Statistikansicht (UnifiedStatsView) für alle Spiele inkl. Goldbeutel- und Varianten-Umschalter eingeführt
- Animiertes GothSwitch-Widget implementiert und optionale Button-Hover-Tooltips (Helvetica) an Settings gekoppelt
- Blackjack- & Poker-Tische auf Vollbild-Canvas umgebaut (kompakter Pot, dynamische Boxbreiten, spoilerfreie Poker-Kartenreferenz neben Spieler-Hand)
- Architektur-Cleanup (strikt 1 Klasse pro Datei: PokerHandsOverlay & SolitaireCard separiert) sowie AST-Prüfskripte für i18n und Multi-Class-Checks ergänzt
This commit is contained in:
thw 2026-11-21 02:20:50 +01:00
parent 4c29eda3c3
commit 3bccab12fa
43 changed files with 5012 additions and 1821 deletions

View File

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

View File

@ -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,13 +45,13 @@ 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
@ -70,7 +64,6 @@ if [ "$HOST_OS" = "linux" ]; then
echo "🔒 Fehlende Systempakete erkannt – fordere sudo an..."
exec sudo -E bash "$SCRIPT_PATH" "${ORIG_ARGS[@]}"
fi
fi
if [ "${EUID:-$(id -u)}" -eq 0 ] && [ -n "${SUDO_USER:-}" ]; then
REAL_USER="$SUDO_USER"
@ -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
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

View File

@ -0,0 +1,862 @@
#Requires -Version 5.1
<#
.SYNOPSIS
Tiefen-Pruefung aller t(key, *args) i18n-Aufrufe im gesamten Projekt
inklusive verschachtelter Konstanten, Variablenketten, Modul-Importen,
Tupel/Dict-Unpacking, Funktionsparametern und f-Strings.
#>
param(
[switch]$RebuildDb,
[switch]$ShowDynamic
)
$ErrorActionPreference = "Stop"
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Definition
$ProjectRoot = (Resolve-Path (Join-Path $ScriptDir "..")).Path
function Find-PythonExe {
$venvPy = Join-Path $ProjectRoot ".venv\Scripts\python.exe"
if (Test-Path $venvPy) { return $venvPy }
foreach ($cmd in @("python", "python3")) {
$found = Get-Command $cmd -ErrorAction SilentlyContinue
if ($found) { return $found.Source }
}
foreach ($candidate in @(
"C:\Python311\python.exe",
"C:\Python312\python.exe",
"$env:LocalAppData\Programs\Python\Python311\python.exe",
"$env:ProgramFiles\Python311\python.exe"
)) {
if (Test-Path $candidate) { return $candidate }
}
throw "Keine Python-Installation gefunden!"
}
$PyExe = Find-PythonExe
if ($RebuildDb) {
$rebuildScript = Join-Path $ProjectRoot "build_scripts\rebuild_internal_db.py"
if (-not (Test-Path $rebuildScript)) {
$rebuildScript = Join-Path $ProjectRoot "rebuild_internal_db.py"
}
if (Test-Path $rebuildScript) {
Write-Host "---> Aktualisiere vorab internal_base.db..." -ForegroundColor Cyan
& $PyExe $rebuildScript
}
}
$AnalyzerPy = @'
# -*- coding: utf-8 -*-
import ast
import os
import re
import sqlite3
import sys
from pathlib import Path
ROOT = Path(sys.argv[1]).resolve()
SHOW_DYNAMIC = "--show-dynamic" in sys.argv[2:]
EXCLUDE_DIRS = {".git", ".venv", ".venv_build_win", ".venv_build_macos", "build", "dist", "__pycache__"}
SQL_DIR = ROOT / "resources" / "code_res" / "sql"
DB_PATH = ROOT / "resources" / "code_res" / "internal_base.db"
# ---------------------------------------------------------------------------
# 1. SQL & SQLite-DB Uebersetzungen einlesen
# ---------------------------------------------------------------------------
def load_sql_translations(sql_dir: Path):
sql_map = {} # key -> {"DE": val, "EN": val}
variants = set()
if not sql_dir.is_dir():
return sql_map, variants
tuple_re = re.compile(
r"\(\s*'((?:''|[^'])*)'\s*,\s*'(DE|EN)'\s*,\s*'((?:''|[^'])*)'\s*\)"
)
var_re = re.compile(
r"\(\s*\d+\s*,\s*'[^']*'\s*,\s*'[^']*'\s*,\s*'([^']+)'\s*,"
)
for sql_file in sorted(sql_dir.glob("*.sql")):
content = sql_file.read_text(encoding="utf-8", errors="replace")
for m in tuple_re.finditer(content):
k = m.group(1).replace("''", "'")
lang = m.group(2)
val = m.group(3).replace("''", "'")
sql_map.setdefault(k, {})[lang] = val
for vm in var_re.finditer(content):
variants.add(vm.group(1))
return sql_map, variants
def load_db_translations(db_path: Path):
db_map = {}
if not db_path.is_file():
return db_map
conn = sqlite3.connect(f"{db_path.as_uri()}?mode=ro", uri=True)
try:
for k, lang, val in conn.execute("SELECT key, lang, val FROM base_i18n"):
db_map.setdefault(k, {})[lang] = val
finally:
conn.close()
return db_map
# ---------------------------------------------------------------------------
# 2. Abstrakte Werte fuer tiefenverschachtelte Konstanten- & Datenfluss-Analyse
# ---------------------------------------------------------------------------
class Val:
"""Repräsentiert mögliche String-Werte, Tupel/Listen, Dicts oder f-String-Muster."""
__slots__ = ("strings", "patterns", "items", "mapping")
def __init__(self, strings=None, patterns=None, items=None, mapping=None):
self.strings = set(strings) if strings else set()
self.patterns = set(patterns) if patterns else set()
self.items = list(items) if items else [] # list[Val] fuer Tuple/List
self.mapping = dict(mapping) if mapping else {} # dict[str, Val] fuer Dict
def copy(self):
return Val(
set(self.strings),
set(self.patterns),
[v.copy() for v in self.items],
{k: v.copy() for k, v in self.mapping.items()},
)
def merge(self, other: "Val") -> bool:
if other is None:
return False
changed = False
before_s = len(self.strings)
self.strings |= other.strings
if len(self.strings) != before_s:
changed = True
before_p = len(self.patterns)
self.patterns |= other.patterns
if len(self.patterns) != before_p:
changed = True
if len(other.items) > len(self.items):
for i in range(len(self.items), len(other.items)):
self.items.append(other.items[i].copy())
changed = True
for i in range(min(len(self.items), len(other.items))):
if self.items[i].merge(other.items[i]):
changed = True
for k, ov in other.mapping.items():
if k not in self.mapping:
self.mapping[k] = ov.copy()
changed = True
elif self.mapping[k].merge(ov):
changed = True
return changed
def all_leaf_strings(self) -> set:
out = set(self.strings)
for it in self.items:
out |= it.all_leaf_strings()
for mv in self.mapping.values():
out |= mv.all_leaf_strings()
return out
@property
def is_empty(self) -> bool:
return not (self.strings or self.patterns or self.items or self.mapping)
# ---------------------------------------------------------------------------
# 3. Projektweite Python-Dateien parsen & Modulnamen bestimmen
# ---------------------------------------------------------------------------
def collect_py_files(root: Path):
modules = {} # mod_name -> (Path, ast.Module)
for dirpath, dirnames, filenames in os.walk(root):
dirnames[:] = [d for d in dirnames if d not in EXCLUDE_DIRS]
for fn in sorted(filenames):
if not fn.endswith(".py"):
continue
fpath = Path(dirpath) / fn
rel = fpath.relative_to(root)
parts = list(rel.with_suffix("").parts)
if parts[-1] == "__init__":
parts = parts[:-1]
mod_name = ".".join(parts) if parts else "__root__"
try:
src = fpath.read_text(encoding="utf-8", errors="replace")
tree = ast.parse(src, filename=str(fpath))
modules[mod_name] = (fpath, tree)
except SyntaxError as exc:
print(f"[SYNTAX-WARNUNG] {rel}: {exc}")
return modules
class ProjectAnalyzer:
def __init__(self, modules: dict):
self.modules = modules
# Globale Modul-Umgebungen: mod_name -> {var_name: Val}
self.mod_envs = {m: {} for m in modules}
# Klassen-Attribute & Instanz-Felder (self.xyz): (mod_name, cls_name) -> {attr: Val}
self.cls_attrs = {}
# Funktions-/Methoden-Parameter aus Aufrufen: func_key -> {param_name: Val}
self.func_param_envs = {}
# Funktions-Definitionen nach Schluessel fuer Call-Propagation
self.func_defs = {} # (mod_name, cls_name_or_None, func_name) -> ast.FunctionDef
# Import-Aliase fuer i18n.t pro Modul: mod_name -> (set_of_direct_t_names, set_of_i18n_mod_aliases)
self.t_aliases = {m: (set(), set()) for m in modules}
# Modul-Aliase (import foo.bar as fb): mod_name -> {alias: target_mod}
self.mod_imports = {m: {} for m in modules}
# From-Importe (from foo import BAR as B): mod_name -> {local_name: (target_mod, orig_name)}
self.sym_imports = {m: {} for m in modules}
self._index_definitions_and_imports()
def _resolve_import_target(self, cur_mod: str, module_str: str | None, level: int) -> str:
if level == 0:
return module_str or ""
cur_parts = cur_mod.split(".")[:-1]
up = max(0, level - 1)
base = cur_parts[: max(0, len(cur_parts) - up)]
if module_str:
base.extend(module_str.split("."))
return ".".join(base)
def _index_definitions_and_imports(self):
for mod_name, (_fpath, tree) in self.modules.items():
t_direct, t_mods = self.t_aliases[mod_name]
if mod_name.endswith(".i18n") or mod_name == "i18n":
t_direct.add("t")
for node in tree.body:
if isinstance(node, ast.Import):
for alias in node.names:
asname = alias.asname or alias.name.split(".")[0]
if alias.name in self.modules:
self.mod_imports[mod_name][asname] = alias.name
if alias.name.endswith(".i18n") or alias.name == "i18n":
t_mods.add(asname)
elif isinstance(node, ast.ImportFrom):
target_mod = self._resolve_import_target(mod_name, node.module, node.level)
is_i18n = target_mod.endswith(".i18n") or target_mod == "i18n"
for alias in node.names:
local = alias.asname or alias.name
if is_i18n and alias.name == "t":
t_direct.add(local)
full_submod = f"{target_mod}.{alias.name}" if target_mod else alias.name
if full_submod in self.modules:
self.mod_imports[mod_name][local] = full_submod
else:
self.sym_imports[mod_name][local] = (target_mod, alias.name)
elif isinstance(node, ast.FunctionDef):
self.func_defs[(mod_name, None, node.name)] = node
elif isinstance(node, ast.ClassDef):
self.cls_attrs.setdefault((mod_name, node.name), {})
for item in node.body:
if isinstance(item, ast.FunctionDef):
self.func_defs[(mod_name, node.name, item.name)] = item
def eval_expr(self, node, mod_name: str, local_env: dict, cur_cls: str | None = None) -> Val:
if node is None:
return Val()
# String- oder Zahlen-Literal
if isinstance(node, ast.Constant):
if isinstance(node.value, (str, int, float)) and not isinstance(node.value, bool):
return Val(strings={str(node.value)})
return Val()
# Variablen-Name (Lokal -> Klasse -> Modul -> Import)
if isinstance(node, ast.Name):
nm = node.id
if nm in local_env:
return local_env[nm].copy()
if cur_cls and nm in self.cls_attrs.get((mod_name, cur_cls), {}):
return self.cls_attrs[(mod_name, cur_cls)][nm].copy()
if nm in self.mod_envs.get(mod_name, {}):
return self.mod_envs[mod_name][nm].copy()
if nm in self.sym_imports.get(mod_name, {}):
t_mod, orig = self.sym_imports[mod_name][nm]
if t_mod in self.mod_envs and orig in self.mod_envs[t_mod]:
return self.mod_envs[t_mod][orig].copy()
return Val()
# Attribut-Zugriff: self.xyz oder modul.KONSTANTE oder Klasse.KONSTANTE
if isinstance(node, ast.Attribute):
if isinstance(node.value, ast.Name):
base = node.value.id
if base == "self" and cur_cls:
return self.cls_attrs.get((mod_name, cur_cls), {}).get(node.attr, Val()).copy()
if base in self.mod_imports.get(mod_name, {}):
t_mod = self.mod_imports[mod_name][base]
return self.mod_envs.get(t_mod, {}).get(node.attr, Val()).copy()
if (mod_name, base) in self.cls_attrs:
return self.cls_attrs[(mod_name, base)].get(node.attr, Val()).copy()
if base in self.sym_imports.get(mod_name, {}):
t_mod, orig_cls = self.sym_imports[mod_name][base]
if (t_mod, orig_cls) in self.cls_attrs:
return self.cls_attrs[(t_mod, orig_cls)].get(node.attr, Val()).copy()
return Val()
# Tupel / Liste / Set
if isinstance(node, (ast.Tuple, ast.List, ast.Set)):
elems = [self.eval_expr(e, mod_name, local_env, cur_cls) for e in node.elts]
v = Val(items=elems)
for el in elems:
v.strings |= el.strings
v.patterns |= el.patterns
return v
# Dict-Literal
if isinstance(node, ast.Dict):
mp = {}
all_s = set()
for k_node, v_node in zip(node.keys, node.values):
vv = self.eval_expr(v_node, mod_name, local_env, cur_cls)
all_s |= vv.strings
if k_node is not None:
kv = self.eval_expr(k_node, mod_name, local_env, cur_cls)
for ks in kv.strings:
mp.setdefault(ks, Val()).merge(vv)
return Val(strings=all_s, mapping=mp)
# Subscript: d[key] oder tup[0]
if isinstance(node, ast.Subscript):
container = self.eval_expr(node.value, mod_name, local_env, cur_cls)
idx_val = self.eval_expr(node.slice, mod_name, local_env, cur_cls)
out = Val()
if container.mapping:
if idx_val.strings:
for ks in idx_val.strings:
if ks in container.mapping:
out.merge(container.mapping[ks])
else:
for mv in container.mapping.values():
out.merge(mv)
if container.items:
matched_idx = False
for ks in idx_val.strings:
if ks.lstrip("-").isdigit():
i = int(ks)
if -len(container.items) <= i < len(container.items):
out.merge(container.items[i])
matched_idx = True
if not matched_idx and not container.mapping:
for it in container.items:
out.merge(it)
return out
# Ternary: a if cond else b
if isinstance(node, ast.IfExp):
res = self.eval_expr(node.body, mod_name, local_env, cur_cls)
res.merge(self.eval_expr(node.orelse, mod_name, local_env, cur_cls))
return res
# BoolOp: a or b
if isinstance(node, ast.BoolOp):
res = Val()
for v_node in node.values:
res.merge(self.eval_expr(v_node, mod_name, local_env, cur_cls))
return res
# String-Verkettung: "variant_" + key
if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
lv = self.eval_expr(node.left, mod_name, local_env, cur_cls)
rv = self.eval_expr(node.right, mod_name, local_env, cur_cls)
return self._combine_parts([lv, rv])
# f-String: f"variant_{self.variant_key}"
if isinstance(node, ast.JoinedStr):
parts = []
for p in node.values:
if isinstance(p, ast.Constant) and isinstance(p.value, str):
parts.append(Val(strings={p.value}))
elif isinstance(p, ast.FormattedValue):
sub = self.eval_expr(p.value, mod_name, local_env, cur_cls)
if sub.strings:
parts.append(Val(strings=sub.strings))
else:
parts.append(Val(patterns={".*"}))
return self._combine_parts(parts)
# Aufrufe wie dict(STAT_GAME_GROUPS) oder my_dict.get(key, default)
if isinstance(node, ast.Call):
if isinstance(node.func, ast.Name) and node.func.id == "dict" and node.args:
arg0 = self.eval_expr(node.args[0], mod_name, local_env, cur_cls)
mp = {}
for pair in arg0.items:
if len(pair.items) >= 2:
for ks in pair.items[0].strings:
mp.setdefault(ks, Val()).merge(pair.items[1])
return Val(mapping=mp)
if isinstance(node.func, ast.Attribute) and node.func.attr == "get":
recv = self.eval_expr(node.func.value, mod_name, local_env, cur_cls)
out = Val()
if recv.mapping:
if node.args:
kv = self.eval_expr(node.args[0], mod_name, local_env, cur_cls)
if kv.strings:
for ks in kv.strings:
if ks in recv.mapping:
out.merge(recv.mapping[ks])
else:
for mv in recv.mapping.values():
out.merge(mv)
if len(node.args) >= 2:
out.merge(self.eval_expr(node.args[1], mod_name, local_env, cur_cls))
return out
return Val()
@staticmethod
def _combine_parts(parts: list) -> Val:
"""Kartesisches Produkt fuer f-Strings / '+'-Verkettung; faellt bei Unbekannten auf Regex-Muster zurueck."""
has_wildcard = any(bool(p.patterns) and not p.strings for p in parts)
if not has_wildcard:
acc = {""}
for p in parts:
if not p.strings:
return Val()
nxt = set()
for prefix in acc:
for s in p.strings:
if len(nxt) < 128:
nxt.add(prefix + s)
acc = nxt
return Val(strings=acc)
regex_pieces = []
for p in parts:
if p.strings and not p.patterns:
escaped = [re.escape(s) for s in sorted(p.strings)]
regex_pieces.append(f"(?:{'|'.join(escaped)})" if len(escaped) > 1 else escaped[0])
else:
regex_pieces.append(".+")
return Val(patterns={f"^{''.join(regex_pieces)}$"})
def _bind_target(self, target, val: Val, mod_name: str, env: dict, cur_cls: str | None, is_mod_scope: bool) -> bool:
changed = False
if isinstance(target, ast.Name):
dest = self.mod_envs[mod_name] if is_mod_scope else env
if target.id not in dest:
dest[target.id] = val.copy()
return not val.is_empty
return dest[target.id].merge(val)
if isinstance(target, ast.Attribute) and cur_cls:
if isinstance(target.value, ast.Name) and target.value.id == "self":
cdict = self.cls_attrs.setdefault((mod_name, cur_cls), {})
if target.attr not in cdict:
cdict[target.attr] = val.copy()
return not val.is_empty
return cdict[target.attr].merge(val)
if isinstance(target, (ast.Tuple, ast.List)):
for idx, sub_t in enumerate(target.elts):
sub_val = val.items[idx] if idx < len(val.items) else Val()
if self._bind_target(sub_t, sub_val, mod_name, env, cur_cls, is_mod_scope):
changed = True
return changed
def _propagate_call_args(self, call_node: ast.Call, mod_name: str, local_env: dict, cur_cls: str | None) -> bool:
"""Leitet Argument-Werte von Aufrufstellen an Funktions- und Konstruktor-Parameter weiter."""
target_key = None
is_method_or_init = False
if isinstance(call_node.func, ast.Name):
fn = call_node.func.id
if (mod_name, None, fn) in self.func_defs:
target_key = (mod_name, None, fn)
elif (mod_name, fn, "__init__") in self.func_defs:
target_key = (mod_name, fn, "__init__")
is_method_or_init = True
elif fn in self.sym_imports.get(mod_name, {}):
t_mod, orig = self.sym_imports[mod_name][fn]
if (t_mod, None, orig) in self.func_defs:
target_key = (t_mod, None, orig)
elif (t_mod, orig, "__init__") in self.func_defs:
target_key = (t_mod, orig, "__init__")
is_method_or_init = True
elif isinstance(call_node.func, ast.Attribute):
if isinstance(call_node.func.value, ast.Name) and call_node.func.value.id == "self" and cur_cls:
mname = call_node.func.attr
if (mod_name, cur_cls, mname) in self.func_defs:
target_key = (mod_name, cur_cls, mname)
is_method_or_init = True
if target_key is None:
return False
fdef = self.func_defs[target_key]
param_names = [a.arg for a in fdef.args.args]
if is_method_or_init and param_names and param_names[0] in ("self", "cls"):
param_names = param_names[1:]
penv = self.func_param_envs.setdefault(target_key, {})
changed = False
for i, arg_node in enumerate(call_node.args):
if i < len(param_names):
av = self.eval_expr(arg_node, mod_name, local_env, cur_cls)
if not av.is_empty:
pname = param_names[i]
if pname not in penv:
penv[pname] = av.copy()
changed = True
elif penv[pname].merge(av):
changed = True
for kw in call_node.keywords:
if kw.arg and kw.arg in param_names:
kv = self.eval_expr(kw.value, mod_name, local_env, cur_cls)
if not kv.is_empty:
if kw.arg not in penv:
penv[kw.arg] = kv.copy()
changed = True
elif penv[kw.arg].merge(kv):
changed = True
return changed
def _walk_statements(self, stmts, mod_name: str, env: dict, cur_cls: str | None, is_mod_scope: bool, collect_calls: list | None):
changed = False
for stmt in stmts:
if isinstance(stmt, ast.Assign):
val = self.eval_expr(stmt.value, mod_name, env, cur_cls)
for tgt in stmt.targets:
if self._bind_target(tgt, val, mod_name, env, cur_cls, is_mod_scope):
changed = True
elif isinstance(stmt, ast.AnnAssign) and stmt.value is not None:
val = self.eval_expr(stmt.value, mod_name, env, cur_cls)
if self._bind_target(stmt.target, val, mod_name, env, cur_cls, is_mod_scope):
changed = True
elif isinstance(stmt, ast.For):
iter_val = self._eval_iter_items(stmt.iter, mod_name, env, cur_cls)
for elem_val in iter_val:
if self._bind_target(stmt.target, elem_val, mod_name, env, cur_cls, False):
changed = True
if self._walk_statements(stmt.body, mod_name, env, cur_cls, False, collect_calls):
changed = True
if self._walk_statements(stmt.orelse, mod_name, env, cur_cls, False, collect_calls):
changed = True
elif isinstance(stmt, (ast.If, ast.While)):
if self._walk_statements(stmt.body, mod_name, env, cur_cls, is_mod_scope, collect_calls):
changed = True
if self._walk_statements(stmt.orelse, mod_name, env, cur_cls, is_mod_scope, collect_calls):
changed = True
elif isinstance(stmt, ast.With):
if self._walk_statements(stmt.body, mod_name, env, cur_cls, is_mod_scope, collect_calls):
changed = True
elif isinstance(stmt, ast.Try):
if self._walk_statements(stmt.body, mod_name, env, cur_cls, is_mod_scope, collect_calls):
changed = True
for h in stmt.handlers:
if self._walk_statements(h.body, mod_name, env, cur_cls, is_mod_scope, collect_calls):
changed = True
if self._walk_statements(stmt.orelse, mod_name, env, cur_cls, is_mod_scope, collect_calls):
changed = True
if self._walk_statements(stmt.finalbody, mod_name, env, cur_cls, is_mod_scope, collect_calls):
changed = True
elif isinstance(stmt, ast.ClassDef):
cls_env = {}
for c_stmt in stmt.body:
if isinstance(c_stmt, ast.Assign):
val = self.eval_expr(c_stmt.value, mod_name, cls_env, stmt.name)
for tgt in c_stmt.targets:
if isinstance(tgt, ast.Name):
cdict = self.cls_attrs.setdefault((mod_name, stmt.name), {})
if tgt.id not in cdict:
cdict[tgt.id] = val.copy()
changed = changed or (not val.is_empty)
elif cdict[tgt.id].merge(val):
changed = True
elif isinstance(c_stmt, ast.FunctionDef):
if self._analyze_function(c_stmt, mod_name, env, stmt.name, collect_calls):
changed = True
elif isinstance(stmt, ast.FunctionDef):
if self._analyze_function(stmt, mod_name, env, cur_cls, collect_calls):
changed = True
# Ausdruecke innerhalb des aktuellen Statements (ohne verschachtelte defs/classes) scannen
if not isinstance(stmt, (ast.FunctionDef, ast.ClassDef, ast.For, ast.If, ast.While, ast.With, ast.Try)):
if self._scan_expr_tree(stmt, mod_name, env, cur_cls, collect_calls):
changed = True
elif isinstance(stmt, (ast.If, ast.While)):
if self._scan_expr_tree(stmt.test, mod_name, env, cur_cls, collect_calls):
changed = True
return changed
def _eval_iter_items(self, iter_node, mod_name: str, env: dict, cur_cls: str | None) -> list:
"""Extrahiert Element-Werte aus Schleifen wie `for i, (a, b) in enumerate(STAT_FIELD_KEYS):`."""
if isinstance(iter_node, ast.Call) and isinstance(iter_node.func, ast.Name):
fn = iter_node.func.id
if fn == "enumerate" and iter_node.args:
sub_items = self._eval_iter_items(iter_node.args[0], mod_name, env, cur_cls)
return [Val(items=[Val(strings={str(i)}), it]) for i, it in enumerate(sub_items)]
if fn in ("reversed", "sorted", "list", "tuple") and iter_node.args:
return self._eval_iter_items(iter_node.args[0], mod_name, env, cur_cls)
if fn == "range":
nums = [self.eval_expr(a, mod_name, env, cur_cls) for a in iter_node.args]
if len(nums) == 1 and len(nums[0].strings) == 1 and list(nums[0].strings)[0].isdigit():
n = min(32, int(list(nums[0].strings)[0]))
return [Val(strings={str(i)}) for i in range(n)]
v = self.eval_expr(iter_node, mod_name, env, cur_cls)
if v.items:
return v.items
if v.strings:
return [Val(strings={s}) for s in v.strings]
return []
def _analyze_function(self, fnode: ast.FunctionDef, mod_name: str, outer_env: dict, cur_cls: str | None, collect_calls: list | None) -> bool:
f_env = {k: v.copy() for k, v in outer_env.items()}
fkey = (mod_name, cur_cls, fnode.name)
# Default-Parameterwerte binden
all_args = fnode.args.args
defaults = fnode.args.defaults
if defaults:
offset = len(all_args) - len(defaults)
for idx, d_node in enumerate(defaults):
pname = all_args[offset + idx].arg
f_env[pname] = self.eval_expr(d_node, mod_name, outer_env, cur_cls)
# Aus Aufrufstellen propagierte Parameterwerte einmischen
for pname, pval in self.func_param_envs.get(fkey, {}).items():
if pname in f_env:
f_env[pname].merge(pval)
else:
f_env[pname] = pval.copy()
return self._walk_statements(fnode.body, mod_name, f_env, cur_cls, False, collect_calls)
def _is_t_call(self, call_node: ast.Call, mod_name: str) -> bool:
t_direct, t_mods = self.t_aliases[mod_name]
if isinstance(call_node.func, ast.Name) and call_node.func.id in t_direct:
return True
if (
isinstance(call_node.func, ast.Attribute)
and call_node.func.attr == "t"
and isinstance(call_node.func.value, ast.Name)
and call_node.func.value.id in t_mods
):
return True
return False
def _scan_expr_tree(self, root_node, mod_name: str, env: dict, cur_cls: str | None, collect_calls: list | None) -> bool:
changed = False
def visit(n, cur_env):
nonlocal changed
if n is None or isinstance(n, (ast.FunctionDef, ast.ClassDef)):
return
if isinstance(n, ast.Lambda):
l_env = {k: v.copy() for k, v in cur_env.items()}
l_args = n.args.args
l_defs = n.args.defaults
if l_defs:
off = len(l_args) - len(l_defs)
for i, dn in enumerate(l_defs):
l_env[l_args[off + i].arg] = self.eval_expr(dn, mod_name, cur_env, cur_cls)
visit(n.body, l_env)
return
if isinstance(n, (ast.ListComp, ast.SetComp, ast.GeneratorExp, ast.DictComp)):
c_env = {k: v.copy() for k, v in cur_env.items()}
for gen in n.generators:
visit(gen.iter, c_env)
for elem_v in self._eval_iter_items(gen.iter, mod_name, c_env, cur_cls):
self._bind_target(gen.target, elem_v, mod_name, c_env, cur_cls, False)
for if_n in gen.ifs:
visit(if_n, c_env)
if isinstance(n, ast.DictComp):
visit(n.key, c_env)
visit(n.value, c_env)
else:
visit(n.elt, c_env)
return
if isinstance(n, ast.Call):
if collect_calls is None:
if self._propagate_call_args(n, mod_name, cur_env, cur_cls):
changed = True
elif self._is_t_call(n, mod_name) and n.args:
key_node = n.args[0]
resolved = self.eval_expr(key_node, mod_name, cur_env, cur_cls)
has_star = any(isinstance(a, ast.Starred) for a in n.args[1:])
pos_argc = None if has_star else (len(n.args) - 1)
try:
expr_src = ast.unparse(key_node)
except Exception:
expr_src = "<expr>"
collect_calls.append({
"mod": mod_name,
"file": self.modules[mod_name][0],
"line": getattr(n, "lineno", 0),
"expr": expr_src,
"val": resolved,
"argc": pos_argc,
})
for child in ast.iter_child_nodes(n):
visit(child, cur_env)
visit(root_node, env)
return changed
def run_analysis(self, max_passes: int = 5):
for _ in range(max_passes):
any_change = False
for mod_name, (_fpath, tree) in self.modules.items():
if self._walk_statements(tree.body, mod_name, {}, None, True, collect_calls=None):
any_change = True
if not any_change:
break
calls = []
for mod_name, (_fpath, tree) in self.modules.items():
self._walk_statements(tree.body, mod_name, {}, None, True, collect_calls=calls)
return calls
# ---------------------------------------------------------------------------
# 4. Auswertung & Bericht
# ---------------------------------------------------------------------------
sql_map, sql_variants = load_sql_translations(SQL_DIR)
db_map = load_db_translations(DB_PATH)
ref_map = sql_map if sql_map else db_map
modules = collect_py_files(ROOT)
analyzer = ProjectAnalyzer(modules)
t_calls = analyzer.run_analysis()
missing_keys = [] # (key, rel_file, line, expr, missing_where)
incomplete_langs = [] # (key, missing_lang)
db_drift_keys = [] # Keys in SQL, aber noch nicht in internal_base.db
placeholder_issues = [] # (key, rel_file, line, lang, max_ph, given_argc)
unmatched_patterns = [] # (pattern, rel_file, line, expr)
unresolved_dynamic = [] # (rel_file, line, expr)
# 1. Alle SQL-Keys auf Vollständigkeit (DE & EN) und DB-Sync prüfen
for k in sorted(sql_map.keys()):
langs = sql_map[k]
if "DE" not in langs:
incomplete_langs.append((k, "DE fehlt in SQL"))
if "EN" not in langs:
incomplete_langs.append((k, "EN fehlt in SQL"))
if db_map and (k not in db_map or "DE" not in db_map[k] or "EN" not in db_map[k]):
db_drift_keys.append(k)
# Prüfen, ob jede registrierte Spielvariante ein 'variant_<key>' hat
for vk in sorted(sql_variants):
full_vk = f"variant_{vk}"
if full_vk not in ref_map:
missing_keys.append((full_vk, "resources/code_res/sql/*.sql", 0, f"game_variants.{vk}", "FEHLT in base_i18n"))
ph_re = re.compile(r"\{(\d+)\}")
checked_unique_keys = set()
for entry in t_calls:
rel_file = entry["file"].relative_to(ROOT).as_posix()
line = entry["line"]
expr = entry["expr"]
val: Val = entry["val"]
argc = entry["argc"]
if val.strings:
for k in sorted(val.strings):
checked_unique_keys.add(k)
in_sql = k in sql_map
in_db = (k in db_map) if db_map else in_sql
if not in_sql and not in_db:
missing_keys.append((k, rel_file, line, expr, "FEHLT in SQL & DB"))
elif not in_sql and in_db:
missing_keys.append((k, rel_file, line, expr, "Nur in DB, FEHLT in SQL-Dateien"))
else:
src_entry = sql_map.get(k) or db_map.get(k, {})
if argc is not None:
for lg in ("DE", "EN"):
txt = src_entry.get(lg, "")
idxs = [int(m.group(1)) for m in ph_re.finditer(txt)]
if idxs and max(idxs) >= argc:
placeholder_issues.append((k, rel_file, line, lg, max(idxs) + 1, argc))
elif val.patterns:
for pat in sorted(val.patterns):
rx = re.compile(pat)
matches = [k for k in ref_map if rx.match(k)]
if not matches:
unmatched_patterns.append((pat, rel_file, line, expr))
else:
checked_unique_keys.update(matches)
else:
unresolved_dynamic.append((rel_file, line, expr))
print("=" * 74)
print(" GOTH CARDGAME COLLECTION - i18n TIEFEN-PRUEFUNG (AST + KONSTANTEN)")
print("=" * 74)
print(f" Gepruefte Python-Module : {len(modules)}")
print(f" Gefundene t(...)-Aufrufe: {len(t_calls)} ({len(checked_unique_keys)} eindeutige Keys aufgeloest)")
print(f" Keys in SQL-Dateien : {len(sql_map)} | Keys in internal_base.db: {len(db_map)}")
print("-" * 74)
has_errors = False
if missing_keys:
has_errors = True
print(f"\n[FEHLER] {len(missing_keys)} fehlende i18n-Keys im Code gefunden:")
for k, rf, ln, ex, reason in missing_keys:
trace = f" (aus `{ex}`)" if ex not in (f"'{k}'", f'"{k}"') else ""
print(f" - '{k}' -> {rf}:{ln}{trace} [{reason}]")
if unmatched_patterns:
has_errors = True
print(f"\n[FEHLER] {len(unmatched_patterns)} f-String-Muster ohne jeglichen Treffer in SQL/DB:")
for pat, rf, ln, ex in unmatched_patterns:
print(f" - Muster {pat} aus `{ex}` -> {rf}:{ln}")
if incomplete_langs:
has_errors = True
print(f"\n[FEHLER] {len(incomplete_langs)} unvollstaendige Sprach-Paare (DE/EN):")
for k, msg in incomplete_langs:
print(f" - '{k}': {msg}")
if placeholder_issues:
has_errors = True
print(f"\n[WARNUNG] {len(placeholder_issues)} Platzhalter-Abweichungen ({{0}}, {{1}}, ...):")
for k, rf, ln, lg, need_n, got_n in placeholder_issues:
print(f" - '{k}' [{lg}] erwartet {need_n} Argument(e), Aufruf uebergibt {got_n} -> {rf}:{ln}")
if db_drift_keys:
print(f"\n[HINWEIS] {len(db_drift_keys)} Key(s) stehen in .sql, fehlen aber noch in internal_base.db:")
for k in db_drift_keys[:15]:
print(f" - '{k}'")
if len(db_drift_keys) > 15:
print(f" ... und {len(db_drift_keys) - 15} weitere.")
print(" -> Tipp: `python build_scripts/rebuild_internal_db.py` oder `-RebuildDb` ausfuehren!")
if SHOW_DYNAMIC and unresolved_dynamic:
print(f"\n[INFO] {len(unresolved_dynamic)} rein dynamische Laufzeit-Aufrufe:")
for rf, ln, ex in unresolved_dynamic:
print(f" - {rf}:{ln} -> t({ex})")
if not has_errors and not db_drift_keys:
print("\n[OK] Alles sauber! Alle aufgeloesten t(...)-Keys existieren vollstaendig in DE & EN.")
print("=" * 74)
sys.exit(1 if has_errors else 0)
'@
$extraArgs = @($ProjectRoot)
if ($ShowDynamic) { $extraArgs += "--show-dynamic" }
$AnalyzerPy | & $PyExe - @extraArgs
exit $LASTEXITCODE

View File

@ -0,0 +1,116 @@
#Requires -Version 5.1
<#
.SYNOPSIS
Prueft alle Python-Dateien im Projekt auf mehr als eine Klassendefinition
und gibt den vollen Dateipfad samt Klassennamen aus.
#>
param(
[string]$TargetDir = "",
[switch]$IncludeNested
)
$ErrorActionPreference = "Stop"
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
if ([string]::IsNullOrWhiteSpace($TargetDir)) {
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Definition
# Falls das Skript in build_scripts/ liegt, automatisch eine Ebene hoeher starten, sonst im aktuellen Ordner
if ((Split-Path -Leaf $ScriptDir) -ieq "build_scripts") {
$RootPath = (Resolve-Path (Join-Path $ScriptDir "..")).Path
} else {
$RootPath = (Resolve-Path $ScriptDir).Path
}
} else {
$RootPath = (Resolve-Path $TargetDir).Path
}
$ExcludeDirs = @(".git", ".venv", ".venv_build_win", ".venv_build_macos", "build", "dist", "__pycache__")
# Versuche Python fuer 100% exaktes AST-Parsing zu finden, sonst Fallback auf Regex
$PyExe = $null
$venvPy = Join-Path $RootPath ".venv\Scripts\python.exe"
if (Test-Path $venvPy) {
$PyExe = $venvPy
} else {
foreach ($cmd in @("python", "python3")) {
$found = Get-Command $cmd -ErrorAction SilentlyContinue
if ($found) { $PyExe = $found.Source; break }
}
}
if ($PyExe) {
$PyScript = @'
# -*- coding: utf-8 -*-
import ast
import os
import sys
from pathlib import Path
root = Path(sys.argv[1]).resolve()
include_nested = "--nested" in sys.argv[2:]
exclude_dirs = {".git", ".venv", ".venv_build_win", ".venv_build_macos", "build", "dist", "__pycache__"}
def get_classes(tree: ast.AST, nested: bool) -> list[str]:
if not nested:
return [node.name for node in getattr(tree, "body", []) if isinstance(node, ast.ClassDef)]
found = []
def walk_node(n, prefix=""):
for child in ast.iter_child_nodes(n):
if isinstance(child, ast.ClassDef):
qual = f"{prefix}.{child.name}" if prefix else child.name
found.append(qual)
walk_node(child, qual)
else:
walk_node(child, prefix)
walk_node(tree)
return found
for dirpath, dirnames, filenames in os.walk(root):
dirnames[:] = sorted(d for d in dirnames if d not in exclude_dirs)
for fn in sorted(filenames):
if not fn.endswith(".py"):
continue
fpath = Path(dirpath) / fn
try:
src = fpath.read_text(encoding="utf-8", errors="replace")
tree = ast.parse(src, filename=str(fpath))
classes = get_classes(tree, include_nested)
if len(classes) > 1:
print(str(fpath))
for cls_name in classes:
print(f"- {cls_name}")
print("")
except SyntaxError:
pass
'@
$pyArgs = @($RootPath)
if ($IncludeNested) { $pyArgs += "--nested" }
$PyScript | & $PyExe - @pyArgs
}
else {
# Reiner PowerShell-Fallback falls kein Python im PATH ist
$ClassRegex = if ($IncludeNested) { '^\s*class\s+([A-Za-z_][A-Za-z0-9_]*)\b' } else { '^class\s+([A-Za-z_][A-Za-z0-9_]*)\b' }
Get-ChildItem -Path $RootPath -Recurse -File -Filter "*.py" | Where-Object {
$full = $_.FullName
$skip = $false
foreach ($ex in $ExcludeDirs) {
if ($full -match ([regex]::Escape("\$ex\"))) { $skip = $true; break }
}
-not $skip
} | Sort-Object FullName | ForEach-Object {
$classes = New-Object System.Collections.Generic.List[string]
foreach ($line in [System.IO.File]::ReadLines($_.FullName)) {
if ($line -match $ClassRegex) {
$classes.Add($Matches[1])
}
}
if ($classes.Count -gt 1) {
Write-Output $_.FullName
foreach ($c in $classes) {
Write-Output "- $c"
}
Write-Output ""
}
}
}

View File

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

View File

@ -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("<Configure>", 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

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,178 @@
# -*- coding: utf-8 -*-
# games/poker/views/poker_hands_overlay.py
from __future__ import annotations
import tkinter as tk
from PIL import Image, ImageTk
from resources.code_res.game_constants import (
ACCENT_GOLD,
BG_COLOR,
FG_COLOR,
FONT_COLOR_BODY_MUTED,
FONT_COLOR_TITLE_MAIN,
FONT_SIZE_HEADING,
RED_SUITS,
SUIT_SYMBOLS,
)
from resources.code_res.i18n import t
from view.widgets.image_button import ImageButton
HAND_REFERENCE_EXAMPLES = (
(1, 9, (("A", "S"), ("K", "S"), ("Q", "S"), ("J", "S"), ("10", "S"))),
(2, 8, (("J", "S"), ("10", "S"), ("9", "S"), ("8", "S"), ("7", "S"))),
(3, 7, (("K", "H"), ("K", "C"), ("K", "D"), ("K", "S"), None)),
(4, 6, (("A", "H"), ("A", "C"), ("A", "D"), ("9", "S"), ("9", "H"))),
(5, 5, (("K", "S"), ("J", "S"), ("8", "S"), ("7", "S"), ("5", "S"))),
(6, 4, (("J", "H"), ("10", "C"), ("9", "D"), ("8", "S"), ("7", "H"))),
(7, 3, (("K", "H"), ("K", "C"), ("K", "D"), None, None)),
(8, 2, (("A", "H"), ("A", "C"), ("9", "D"), ("9", "S"), None)),
(9, 1, (("K", "H"), ("K", "C"), None, None, None)),
(10, 0, (("A", "H"), None, None, None, None)),
)
class PokerHandsOverlay(tk.Canvas):
"""Neutrale Kartenreferenz-Übersicht der 10 Poker-Hände (ohne Spoiler der eigenen Hand)."""
OVL_W = 800
OVL_H = 468
def __init__(self, parent, ctx, on_close):
super().__init__(
parent,
width=self.OVL_W,
height=self.OVL_H,
bg=BG_COLOR,
bd=0,
highlightthickness=0,
)
self.ctx = ctx
self.assets = ctx.assets
self.on_close = on_close
self._photo_refs: list = []
self.place(relx=0.5, rely=0.5, anchor="center")
tk.Widget.tkraise(self)
self._build_content()
def _draw_mini_cards(self, x0: int, y0: int, cards_spec: tuple):
cw, ch, gap = 22, 26, 3
for i, spec in enumerate(cards_spec):
cx = x0 + i * (cw + gap)
if spec is None:
self.create_rectangle(
cx, y0, cx + cw, y0 + ch,
fill="#261321", outline="#4e2942", width=1,
)
else:
rank, suit = spec
fg_col = "#cf3848" if suit in RED_SUITS else "#181421"
sym = SUIT_SYMBOLS.get(suit, suit)
self.create_rectangle(
cx, y0, cx + cw, y0 + ch,
fill="#ede8f5", outline="#8e82a6", width=1,
)
self.create_text(
cx + cw // 2, y0 + 8,
text=rank, font=("Helvetica", 7, "bold"), fill=fg_col,
)
self.create_text(
cx + cw // 2, y0 + 18,
text=sym, font=("Helvetica", 8, "bold"), fill=fg_col,
)
def _build_content(self):
w, h = self.OVL_W, self.OVL_H
bg_src = self.assets.raw_bg_horizontal or self.assets.raw_bg_vertical or self.assets.raw_bg
if bg_src is not None:
bg_ph = ImageTk.PhotoImage(bg_src.resize((w, h), Image.Resampling.BILINEAR))
self._photo_refs.append(bg_ph)
self.create_image(0, 0, image=bg_ph, anchor="nw")
outer = self.assets.get_box_photo("box_big", (w - 6, h - 6))
if outer:
self._photo_refs.append(outer)
self.create_image(w // 2, h // 2, image=outer, anchor="center")
hdr_ph = self.assets.get_goth_text_photo(
t("pk_help_header"),
size_px=FONT_SIZE_HEADING,
color=FONT_COLOR_TITLE_MAIN,
align="center",
)
self._photo_refs.append(hdr_ph)
self.create_image(w // 2, 32, image=hdr_ph, anchor="center")
self.create_text(
w // 2,
60,
text=t("pk_help_general_info"),
font=("Helvetica", 9),
fill=FONT_COLOR_BODY_MUTED,
width=w - 80,
justify="center",
anchor="center",
)
col_w = (w - 76) // 2
row_h = 62
start_y = 86
cell_box_purp = self.assets.get_box_photo("box_purple", (col_w, row_h - 4))
if cell_box_purp:
self._photo_refs.append(cell_box_purp)
for rank_no, cat_id, cards_spec in HAND_REFERENCE_EXAMPLES:
col_idx = 0 if rank_no <= 5 else 1
row_idx = (rank_no - 1) % 5
cx = 30 + col_idx * (col_w + 16) + col_w // 2
cy = start_y + row_idx * row_h + (row_h - 4) // 2
left_edge = cx - col_w // 2
if cell_box_purp:
self.create_image(cx, cy, image=cell_box_purp, anchor="center")
self._draw_mini_cards(left_edge + 14, cy - 13, cards_spec)
raw_name = t(f"pk_hand_{cat_id}").replace("★ ", "").replace(" ★", "")
short_name = raw_name.split(" (")[0]
name_col = ACCENT_GOLD if rank_no == 1 else FG_COLOR
tip_raw = t(f"pk_help_hand_{cat_id}")
tip_short = tip_raw.split(":", 1)[-1].strip() if ":" in tip_raw else tip_raw
txt_x = left_edge + 142
txt_max_w = col_w - 154
self.create_text(
txt_x,
cy - 12,
text=f"{rank_no}. {short_name}",
font=("Helvetica", 9, "bold"),
fill=name_col,
anchor="w",
)
self.create_text(
txt_x,
cy + 9,
text=tip_short,
font=("Helvetica", 8),
fill=FONT_COLOR_BODY_MUTED,
width=txt_max_w,
anchor="w",
)
btn_fire = self.assets.raw_btn_fire or self.assets.raw_btn_purple
close_btn = ImageButton(
self,
t("pk_btn_close_help"),
btn_fire,
btn_fire,
self.on_close,
sound_mgr=self.ctx.sounds,
width=156,
height=34,
style="fire",
)
self.create_window(w // 2, h - 30, window=close_btn, anchor="center")

File diff suppressed because it is too large Load Diff

View File

@ -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("<Configure>", 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
self._frame_ph = self._get_bar_box_photo(
"box_gold_double", frame_w, self.CONTENT_H - 2, scale=0.85
)
except TypeError:
self._frame_ph = self.assets.get_box_photo("box_gold_double", (frame_w, self.CONTENT_H - 2))
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()]
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)
# 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:
seg_ph = self.assets.get_goth_text_photo(
txt, size_px=FONT_SIZE_SMALL_MIN + 1, color=FONT_COLOR_HEADING_SUB, align="left"
)
self._txt_refs.append(seg_ph)
self.create_image(lx, cy, image=seg_ph, anchor="w", tags="bb_txt")
lx += seg_ph.width() + 12
rx_main -= self._calc_btns_width(top_btns)
st_str = (self.status_var.get() or "").replace("•", "-")
if st_str and (right_limit - lx) >= 80:
# 2. Rechte Erweiterungsfläche (nur sichtbar, wenn Buttons nach unten ausgelagert wurden)
if sub_btns:
sub_btns_w = self._calc_btns_width(sub_btns)
r_box_w = sub_btns_w + 26
r_box_right = w - side_inset
r_box_cx = r_box_right - r_box_w // 2
self.create_rectangle(
r_box_right - r_box_w + 4,
sub_top + 4,
r_box_right - 4,
sub_top + self.SUB_BAR_H - 4,
fill="#100d17",
outline="",
tags="bb_sub_frame",
)
self._sub_right_frame_ph = self._get_bar_box_photo(
"box_gold_double", r_box_w, self.SUB_BAR_H, scale=0.72
)
if self._sub_right_frame_ph:
self.create_image(
r_box_cx,
cy_sub,
image=self._sub_right_frame_ph,
anchor="center",
tags="bb_sub_frame",
)
if place_buttons:
rx_sub = r_box_right - 13
for btn in reversed(sub_btns):
bw = btn.pixel_width
bh = min(btn.pixel_height, self.SUB_BAR_H - 6)
btn.place(x=rx_sub - bw, y=cy_sub - bh // 2, width=bw, height=bh)
tk.Widget.tkraise(btn)
rx_sub -= (bw + 6)
if place_buttons:
self._last_btn_split = (
tuple(id(b) for b in top_btns),
tuple(id(b) for b in sub_btns),
)
# 3. Hauptleisten-Text im freien linken Bereich auf der X-Achse zentrieren
min_lx = side_inset + 22
right_limit = rx_main - 14
st_str = (self.status_var.get() or "").replace("•", "|")
segs_w = self._calc_segs_width(top_segs, pipe_step)
st_ph = None
total_txt_w = segs_w
if st_str and (right_limit - (min_lx + segs_w)) >= 90:
avail_st_w = right_limit - (min_lx + segs_w + (pipe_step if top_segs else 0))
st_ph = self.assets.get_goth_text_photo(
st_str,
size_px=FONT_SIZE_SMALL_MIN,
color=UI_ACCENT_AMETHYST,
max_width=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")
self.create_image(lx, txt_cy_main, image=st_ph, anchor="w", tags="bb_txt")
# 4. Linke Erweiterungsfläche (nur sichtbar, wenn Text-Segmente nach unten ausgelagert wurden)
if sub_segs:
sub_txt_w = self._calc_segs_width(sub_segs, pipe_step)
l_box_w = sub_txt_w + 36
l_box_left = side_inset
l_box_cx = l_box_left + l_box_w // 2
self.create_rectangle(
l_box_left + 4,
sub_top + 4,
l_box_left + l_box_w - 4,
sub_top + self.SUB_BAR_H - 4,
fill="#100d17",
outline="",
tags="bb_sub_frame",
)
self._sub_left_frame_ph = self._get_bar_box_photo(
"box_gold_double", l_box_w, self.SUB_BAR_H, scale=0.72
)
if self._sub_left_frame_ph:
self.create_image(
l_box_cx,
cy_sub,
image=self._sub_left_frame_ph,
anchor="center",
tags="bb_sub_frame",
)
sub_lx = l_box_cx - sub_txt_w // 2
for i, seg in enumerate(sub_segs):
if i > 0:
self.create_image(sub_lx + 5, txt_cy_sub, image=pipe_ph, anchor="w", tags="bb_txt")
sub_lx += pipe_step
ph = seg["photo"]
self._txt_refs.append(ph)
self.create_image(sub_lx, txt_cy_sub, image=ph, anchor="w", tags="bb_txt")
sub_lx += ph.width()

View File

@ -0,0 +1,57 @@
# -*- coding: utf-8 -*-
# games/solitaire/base/solitaire_card.py
from __future__ import annotations
from dataclasses import dataclass
from resources.code_res.game_constants import (
CARD_FILE_PATTERN,
RED_SUITS,
SUIT_SYMBOLS,
)
SOLITAIRE_RANKS: tuple[str, ...] = (
"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"
)
RANK_VALUES: dict[str, int] = {rank: idx + 1 for idx, rank in enumerate(SOLITAIRE_RANKS)}
@dataclass
class SolitaireCard:
suit: str
rank: str
face_up: bool = False
deck_id: int = 0
@property
def value(self) -> int:
return RANK_VALUES[self.rank]
@property
def is_red(self) -> bool:
return self.suit in RED_SUITS
@property
def filename(self) -> str:
return CARD_FILE_PATTERN.format(suit=self.suit, rank=self.rank)
@property
def label(self) -> str:
return f"{self.rank}{SUIT_SYMBOLS.get(self.suit, self.suit)}"
def to_dict(self) -> dict:
return {
"s": self.suit,
"r": self.rank,
"u": 1 if self.face_up else 0,
"d": self.deck_id,
}
@classmethod
def from_dict(cls, data: dict) -> SolitaireCard:
return cls(
suit=data["s"],
rank=data["r"],
face_up=bool(data.get("u", 0)),
deck_id=int(data.get("d", 0)),
)

View File

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

Binary file not shown.

View File

@ -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,12 +419,20 @@ 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})'),

View File

@ -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:'),
@ -227,6 +229,22 @@ INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES
('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');
('variant_bj_highstakes', 'EN', 'Blackjack – High Stakes');

View File

@ -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]'),
@ -145,16 +153,16 @@ INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES
('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.'),

Binary file not shown.

After

Width:  |  Height:  |  Size: 908 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 106 KiB

View File

@ -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("<ButtonPress-1>", self._on_mouse_down)
self.bind("<B1-Motion>", self._on_mouse_drag)
self.bind("<ButtonRelease-1>", 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):
if self.winfo_exists():
self.destroy()
if getattr(self.root_window, "_audio_overlay", None) is self:
self.root_window._audio_overlay = None
SettingsDialog = AudioSettingsDialog

View File

@ -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("<Return>", 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("<Enter>", lambda e: (cv.itemconfigure(bg_id, image=hover_img) if hover_img else None, cv.itemconfigure(txt_id, fill=ACCENT_GOLD)))
cv.bind("<Leave>", lambda e: (cv.itemconfigure(bg_id, image=normal_img) if normal_img else None, cv.itemconfigure(txt_id, fill=FG_COLOR)))
cv.bind("<Button-1>", lambda e: (self.sounds.play("click"), on_click()))
return cv

551
view/unified_stats_view.py Normal file
View File

@ -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("<Configure>", self._on_configure)
self.bind("<Destroy>", self._on_destroy)
try:
self._esc_bind_id = self.ctx.root.bind("<Escape>", 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("<Escape>", 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"
)

261
view/widgets/goth_switch.py Normal file
View File

@ -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("<ButtonRelease-1>", self._on_click)
self.bind("<Destroy>", 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")

421
view/widgets/goth_topbar.py Normal file
View File

@ -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("<Configure>", self._on_configure)
self.bind("<Destroy>", self._on_destroy)
try:
self._root_cfg_bind_id = self._root_win.bind(
"<Configure>", 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("<Configure>", 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()

View File

@ -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("<Leave>", self._on_leave)
self.bind("<ButtonPress-1>", self._on_press)
self.bind("<ButtonRelease-1>", self._on_release)
self.bind("<Destroy>", 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
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()
self._cancel_hover_timer()
if ImageButton._active_tip_owner is self:
ImageButton.close_active_hover_tip()