the_goth_cardgame_collection/controller/app_context.py

444 lines
15 KiB
Python
Raw Normal View History

2026-11-14 04:25:51 +00:00
# -*- coding: utf-8 -*-
# controller/app_context.py
from __future__ import annotations
2026-11-14 04:25:51 +00:00
import tkinter as tk
from PIL import Image, ImageTk
2026-11-14 04:25:51 +00:00
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,
)
2026-11-14 04:25:51 +00:00
from resources.code_res.i18n import t
from view.dialogs.audio_settings_dialog import AudioSettingsDialog
from view.widgets.goth_dropdown import GothDropdown
2026-11-14 04:25:51 +00:00
from view.widgets.image_button import ImageButton
BG_SAFE_SIDE_RATIO = getattr(gc, "BG_SAFE_SIDE_RATIO", 0.088)
BG_SAFE_TOP_RATIO = getattr(gc, "BG_SAFE_TOP_RATIO", 0.095)
_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("←", "-")
2026-11-14 04:25:51 +00:00
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")
2026-11-14 04:25:51 +00:00
class AppContext:
def __init__(self, controller, game_folder: str):
self._ctrl = controller
self.game_folder = game_folder
self.root = controller.view
self.assets = controller.view.assets
self.sounds = controller.sounds
@property
def profile(self) -> dict:
return self._ctrl.active_profile
@property
def game_progress(self) -> dict:
return Database.get_game_progress(self.profile["id"], self.game_folder)
def refresh_game_progress(self) -> dict:
return Database.get_game_progress(self.profile["id"], self.game_folder)
def back_to_main_menu(self):
GothDropdown.close_any_open_popup()
2026-11-14 04:25:51 +00:00
self._ctrl.show_main_menu()
def open_audio_settings(self):
GothDropdown.close_any_open_popup()
2026-11-14 04:25:51 +00:00
AudioSettingsDialog.open(self.root, self.assets, self.sounds)
def toggle_language(self, refresh_callback=None):
GothDropdown.close_any_open_popup()
2026-11-14 04:25:51 +00:00
self._ctrl.toggle_language(refresh_callback)
def record_result(
self,
variant_key: str,
won: bool,
duration_sec: float,
points_gained: int = 0,
bj_account_id: int | None = None,
pk_account_id: int | None = None,
2026-11-14 04:25:51 +00:00
) -> tuple[int, int]:
if not self._ctrl.active_profile:
return (1, 1)
pid = self._ctrl.active_profile["id"]
old_lvl, new_lvl = Database.record_game_result(
pid,
variant_key,
won,
duration_sec,
points_gained,
bj_account_id=bj_account_id,
pk_account_id=pk_account_id,
2026-11-14 04:25:51 +00:00
)
self.sounds.play("end_battle" if new_lvl > old_lvl else ("win" if won else "lose"))
return old_lvl, new_lvl
def build_game_topbar(
self,
parent,
title: str,
on_game_menu=None,
on_stats=None,
stats_enabled: bool = True,
extra_right_text: str = "",
on_lang_refresh=None,
locked_exit: bool = False,
) -> GothTopbar:
bar = GothTopbar(
parent=parent,
ctx=self,
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,
2026-11-14 04:25:51 +00:00
)
bar.pack(fill="x", side="top")
2026-11-14 04:25:51 +00:00
return bar