the_goth_cardgame_collection/controller/app_context.py

324 lines
11 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
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,
)
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
class _CanvasTextLabelProxy:
"""
Kompatibler Proxy für topbar.title_label / extra_label / level_label:
Nimmt .configure(text=..., fg=...) wie ein tk.Label entgegen, zeichnet aber
rahmenlosen PIL-Old-London-Text direkt auf das Topbar-Canvas.
"""
def __init__(self, bar_canvas: "GothTopbar", slot_name: str, text: str, color: str, size_px: int):
self._bar = bar_canvas
self._slot = slot_name
self.text = str(text or "")
self.color = color
self.size_px = size_px
def configure(self, **kwargs):
changed = False
if "text" in kwargs and str(kwargs["text"]) != self.text:
self.text = str(kwargs["text"])
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 GothTopbar(tk.Canvas):
"""Rahmenlose Spiel-Kopfleiste, die den echten Hintergrund-Ausschnitt durchscheinen lässt."""
BAR_HEIGHT = 56
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,
):
super().__init__(
parent,
height=self.BAR_HEIGHT,
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] = (0, 0)
self._left_widgets: list[tuple[tk.Widget, int]] = []
self._right_widgets: list[tuple[tk.Widget, 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=136, height=36, style="amethyst"
)
self._left_widgets.append((b_main, 136))
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=132, height=36, style="amethyst"
)
self._left_widgets.append((b_gmenu, 132))
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=114, height=36,
enabled=stats_enabled, style="amethyst"
)
self._left_widgets.append((self.stats_btn, 114))
b_lang = ImageButton(
self, t("btn_lang"), btn_norm, btn_purp,
lambda: ctx.toggle_language(on_lang_refresh),
sound_mgr=self.sounds, width=112, height=34, style="amethyst"
)
b_audio = ImageButton(
self, t("btn_audio"), btn_norm, btn_purp,
ctx.open_audio_settings, sound_mgr=self.sounds, width=90, height=34, style="amethyst"
)
self._right_widgets.append((b_lang, 112))
self._right_widgets.append((b_audio, 90))
prof = ctx.profile
prog = ctx.game_progress
init_lvl_txt = t(
"level_badge", prof["name"], prog["title"], prog["level"], prog["current_xp"], prog["needed_xp"]
)
self.title_label = _CanvasTextLabelProxy(
self, "title", title, FONT_COLOR_TITLE_MAIN, FONT_SIZE_HEADING
)
self.extra_label = _CanvasTextLabelProxy(
self, "extra", extra_right_text, FONT_COLOR_HEADING_SUB, FONT_SIZE_BODY
)
self.level_label = _CanvasTextLabelProxy(
self, "level", init_lvl_txt, FONT_COLOR_BODY_DEFAULT, max(FONT_SIZE_SMALL_MIN, FONT_SIZE_BODY - 1)
)
self.bind("<Configure>", self._on_configure)
def _render_bg_slice(self, w: int):
root_win = self.winfo_toplevel()
rw = max(w, root_win.winfo_width())
rh = max(self.BAR_HEIGHT, root_win.winfo_height())
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)
cropped = full_scaled.crop((0, 0, w, self.BAR_HEIGHT))
self._bg_slice_photo = ImageTk.PhotoImage(cropped)
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):
w, h = max(1, event.width), max(1, event.height)
if w < 100 or (w, h) == self._last_size:
return
self._last_size = (w, h)
self._render_bg_slice(w)
self._layout_items(w)
def refresh_text_slots(self):
if not self.winfo_exists():
return
w = self.winfo_width()
if w >= 100:
self._layout_items(w)
def _layout_items(self, w: int):
self.delete("topbar_fg")
self.delete("topbar_txt")
self._text_photos.clear()
cy = self.BAR_HEIGHT // 2
pad_x = max(28, int(w * 0.03))
# 1. Linke Navigation (oder Devil's Deal Sperr-Badge)
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, cy, image=lock_ph, anchor="w", tags="topbar_txt")
left_x += lock_ph.width() + 12
else:
for wgt, bw in self._left_widgets:
self.create_window(left_x, cy, window=wgt, anchor="w", tags="topbar_fg")
left_x += bw + 6
# 2. Rechte Buttons (Audio + Sprache) von rechts nach links
right_x = w - pad_x
for wgt, bw in reversed(self._right_widgets):
self.create_window(right_x, cy, window=wgt, anchor="e", tags="topbar_fg")
right_x -= (bw + 6)
# 3. Level-Badge & Gold-Extra-Anzeige links neben den Sprach-/Audio-Buttons
compact = (w < 1380)
lvl_px = FONT_SIZE_SMALL_MIN if compact else self.level_label.size_px
extra_px = FONT_SIZE_SMALL_MIN if compact else self.extra_label.size_px
if self.level_label.text:
lvl_ph = self.assets.get_goth_text_photo(
self.level_label.text, size_px=lvl_px, color=self.level_label.color, align="right"
)
self._text_photos.append(lvl_ph)
self.create_image(right_x - 4, cy, image=lvl_ph, anchor="e", tags="topbar_txt")
right_x -= (lvl_ph.width() + 12)
if self.extra_label.text:
ext_ph = self.assets.get_goth_text_photo(
self.extra_label.text, size_px=extra_px, color=self.extra_label.color, align="right"
)
self._text_photos.append(ext_ph)
self.create_image(right_x - 2, cy, image=ext_ph, anchor="e", tags="topbar_txt")
right_x -= (ext_ph.width() + 12)
# 4. Spieltitel mittig im verbleibenden freien Raum
avail_title_w = max(80, right_x - left_x - 12)
if self.title_label.text and avail_title_w >= 90:
t_px = (FONT_SIZE_HEADING - 4) if compact else self.title_label.size_px
title_ph = self.assets.get_goth_text_photo(
self.title_label.text,
size_px=t_px,
color=self.title_label.color,
max_width=avail_title_w,
align="center",
)
self._text_photos.append(title_ph)
title_cx = (left_x + right_x) // 2
self.create_image(title_cx, 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