diff --git a/README.md b/README.md index 03928d9..65ea7ba 100644 --- a/README.md +++ b/README.md @@ -83,7 +83,7 @@ the_goth_cardgame_collection/ │ │ ├── internal_base.sql # Vollständiger SQL-Seed (nur für manuelle DB-Neuerstellung) │ │ └── internal_base.db # Fertig mitgelieferte Read-Only-Stammdatenbank │ ├── fonts/ # Lokale TTF-Schriften (OldLondon.ttf, OldLondonAlternate.ttf) -│ ├── images/ # UI-Grafiken, Banner, Tischhintergründe (poker_table.jpg, general_table.jpg) +│ ├── images/ # UI-Grafiken, Banner, Tischhintergründe (poker_table.png, general_table.jpg) │ │ ├── cards/default/ # Spielkarten-Grafiken & Kartenrücken │ │ └── game_icons/ # Modulspezifische Spiel-Icons (*.ico) für Hauptmenü-Kacheln │ └── sounds/ # Musik (Beyond_The_Iron_Gate, The_Midnight_Hand) & SFX diff --git a/controller/__pycache__/app_context.cpython-311.pyc b/controller/__pycache__/app_context.cpython-311.pyc index 27611a3..1516a30 100644 Binary files a/controller/__pycache__/app_context.cpython-311.pyc and b/controller/__pycache__/app_context.cpython-311.pyc differ diff --git a/controller/app_context.py b/controller/app_context.py index bb567fe..914c6a9 100644 --- a/controller/app_context.py +++ b/controller/app_context.py @@ -6,6 +6,7 @@ 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, @@ -15,32 +16,87 @@ from resources.code_res.game_constants import ( 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.widgets.goth_dropdown import GothDropdown 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("←", "-") + 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): + 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.text = str(text or "") + 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 and str(kwargs["text"]) != self.text: - self.text = str(kwargs["text"]) - changed = True + 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 @@ -50,10 +106,34 @@ class _CanvasTextLabelProxy: config = configure -class GothTopbar(tk.Canvas): - """Rahmenlose Spiel-Kopfleiste, die den echten Hintergrund-Ausschnitt durchscheinen lässt.""" +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() - BAR_HEIGHT = 56 + 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, @@ -67,9 +147,12 @@ class GothTopbar(tk.Canvas): 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_HEIGHT, + height=self._bar_h, bg=BG_COLOR, bd=0, highlightthickness=0, @@ -81,10 +164,10 @@ class GothTopbar(tk.Canvas): self._bg_slice_photo: ImageTk.PhotoImage | None = None self._text_photos: list[ImageTk.PhotoImage] = [] - self._last_size: tuple[int, int] = (0, 0) + self._last_size: tuple[int, int, int] = (0, 0, 0) - self._left_widgets: list[tuple[tk.Widget, int]] = [] - self._right_widgets: list[tuple[tk.Widget, int]] = [] + 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 @@ -93,97 +176,135 @@ class GothTopbar(tk.Canvas): 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" + ctx.back_to_main_menu, sound_mgr=self.sounds, width=110, height=32, style="amethyst" ) - self._left_widgets.append((b_main, 136)) + 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=132, height=36, style="amethyst" + on_game_menu, sound_mgr=self.sounds, width=108, height=32, style="amethyst" ) - self._left_widgets.append((b_gmenu, 132)) + 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=114, height=36, + on_stats, sound_mgr=self.sounds, width=96, height=32, enabled=stats_enabled, style="amethyst" ) - self._left_widgets.append((self.stats_btn, 114)) + 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=112, height=34, style="amethyst" + 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=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"] + 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", title, FONT_COLOR_TITLE_MAIN, FONT_SIZE_HEADING + 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_BODY + self, + "extra", + extra_right_text, + FONT_COLOR_HEADING_SUB, + FONT_SIZE_SMALL_MIN + 1, + sanitizer=sanitize_extra_right_text, ) - self.level_label = _CanvasTextLabelProxy( - self, "level", init_lvl_txt, FONT_COLOR_BODY_DEFAULT, max(FONT_SIZE_SMALL_MIN, FONT_SIZE_BODY - 1) + self.level_label = _LevelBadgeProxy( + self, + color=FONT_COLOR_BODY_DEFAULT, + size_px=FONT_SIZE_SMALL_MIN + 1, ) self.bind("", self._on_configure) + rw = parent.winfo_toplevel().winfo_width() + if rw >= 200: + self._last_size = (rw, self._bar_h, root_h) + self._render_bg_slice(rw, self._bar_h) + self._layout_items(rw, self._bar_h) - def _render_bg_slice(self, w: int): + @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(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: + 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 - 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: + if event.widget is not self: return - self._last_size = (w, h) - self._render_bg_slice(w) - self._layout_items(w) + 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._layout_items(w, self._bar_h) - def _layout_items(self, w: int): + 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() - cy = self.BAR_HEIGHT // 2 - pad_x = max(28, int(w * 0.03)) + 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) - # 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( @@ -193,55 +314,54 @@ class GothTopbar(tk.Canvas): 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 + 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: - self.create_window(left_x, cy, window=wgt, anchor="w", tags="topbar_fg") + bh = wgt.pixel_height + wgt.place(x=left_x, y=btn_cy - bh // 2, width=bw, height=bh) + wgt.lift() 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") + 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) - # 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.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 - 4, cy, image=lvl_ph, anchor="e", tags="topbar_txt") + 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: + 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=extra_px, color=self.extra_label.color, align="right" + self.extra_label.text, + size_px=self.extra_label.size_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) + 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) - # 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 + if self.title_label.text: title_ph = self.assets.get_goth_text_photo( self.title_label.text, - size_px=t_px, + size_px=self.title_label.size_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") - + self.create_image(w // 2, title_cy, image=title_ph, anchor="center", tags="topbar_txt") class AppContext: def __init__(self, controller, game_folder: str): diff --git a/games/blackjack/views/__pycache__/blackjack_menu_view.cpython-311.pyc b/games/blackjack/views/__pycache__/blackjack_menu_view.cpython-311.pyc index 32a5417..56c651b 100644 Binary files a/games/blackjack/views/__pycache__/blackjack_menu_view.cpython-311.pyc and b/games/blackjack/views/__pycache__/blackjack_menu_view.cpython-311.pyc differ diff --git a/games/blackjack/views/__pycache__/blackjack_stats_view.cpython-311.pyc b/games/blackjack/views/__pycache__/blackjack_stats_view.cpython-311.pyc index ed46774..ea52530 100644 Binary files a/games/blackjack/views/__pycache__/blackjack_stats_view.cpython-311.pyc and b/games/blackjack/views/__pycache__/blackjack_stats_view.cpython-311.pyc differ diff --git a/games/blackjack/views/blackjack_menu_view.py b/games/blackjack/views/blackjack_menu_view.py index e4ff71f..9c355fc 100644 --- a/games/blackjack/views/blackjack_menu_view.py +++ b/games/blackjack/views/blackjack_menu_view.py @@ -7,7 +7,7 @@ import tkinter as tk from games.blackjack.views.blackjack_stats_view import BlackjackStatsView from games.blackjack.views.blackjack_table_view import BlackjackTableView -from games.solitaire.base.solitaire_menu_chrome import create_menu_body_canvas +from view.widgets.menu_body_canvas import MenuBodyCanvas from models.database import Database from models.progression import Progression from resources.code_res.game_constants import ( @@ -135,7 +135,7 @@ class BlackjackMenuView: on_lang_refresh=refresh_on_lang_switch, ) - cv = create_menu_body_canvas(self.ctx) + cv = MenuBodyCanvas(self.ctx) 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 @@ -328,7 +328,7 @@ class BlackjackMenuView: table_buttons.append(t_btn) def draw_layout(w: int, h: int): - cv._sync_bg(w, h) # type: ignore[attr-defined] + cv.sync_bg(w, h) cv.delete("fg") self._photo_refs.clear() diff --git a/games/blackjack/views/blackjack_stats_view.py b/games/blackjack/views/blackjack_stats_view.py index 3fd5cf2..555ef73 100644 --- a/games/blackjack/views/blackjack_stats_view.py +++ b/games/blackjack/views/blackjack_stats_view.py @@ -2,7 +2,6 @@ # games/blackjack/views/blackjack_stats_view.py from __future__ import annotations -from games.solitaire.base.solitaire_menu_chrome import create_menu_body_canvas from models.database import Database from resources.code_res.game_constants import ( FONT_COLOR_HEADING_SUB, @@ -10,6 +9,7 @@ from resources.code_res.game_constants import ( ) from resources.code_res.i18n import t from view.widgets.image_button import ImageButton +from view.widgets.menu_body_canvas import MenuBodyCanvas from view.widgets.stats_board_widget import StatsBoardWidget GAME_FOLDER_ID = "blackjack" @@ -48,13 +48,12 @@ class BlackjackStatsView: on_lang_refresh=lambda: self.show(active_acc["id"]), ) - cv = create_menu_body_canvas(self.ctx) + cv = MenuBodyCanvas(self.ctx) 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 acc_btns: list[tuple[ImageButton, int]] = [] - btn_w = 186 for acc in accounts: is_sel = (acc["id"] == active_acc["id"]) btn_lbl = f"{acc['account_name']} ({acc['gold']}g)" @@ -65,11 +64,11 @@ class BlackjackStatsView: btn_fire if is_sel else btn_purp, lambda aid=acc["id"]: self.show(selected_acc_id=aid), sound_mgr=self.ctx.sounds, - width=btn_w, + width=180, height=38, style="fire" if is_sel else "amethyst", ) - acc_btns.append((b, btn_w)) + acc_btns.append((b, b.pixel_width)) bj_variants = Database.get_variants_for_filter(folder_path=GAME_FOLDER_ID) bj_filter_map = {t("bj_filter_all_tables"): None} @@ -84,7 +83,7 @@ class BlackjackStatsView: ) def draw_layout(w: int, h: int): - cv._sync_bg(w, h) # type: ignore[attr-defined] + cv.sync_bg(w, h) cv.delete("fg") self._photo_refs.clear() diff --git a/games/blackjack/views/blackjack_table_view.py b/games/blackjack/views/blackjack_table_view.py index 2361d17..5460567 100644 --- a/games/blackjack/views/blackjack_table_view.py +++ b/games/blackjack/views/blackjack_table_view.py @@ -328,7 +328,7 @@ class BlackjackTableView: ) self.controls_frame.grid(row=0, column=2, sticky="nsew", padx=(6, 0)) - # Canvas für den ovalen Tisch (`poker_table.jpg`) + # Canvas für den ovalen Tisch (`poker_table.png`) self.arena_canvas = tk.Canvas( self.table_frame, bg="#120f18", highlightthickness=1, highlightbackground=SUBTLE_BORDER ) diff --git a/games/poker/README.md b/games/poker/README.md index 1cd908e..2b262f9 100644 --- a/games/poker/README.md +++ b/games/poker/README.md @@ -10,7 +10,7 @@ Das Modul `games/poker/` implementiert **6-Max No-Limit Texas Hold'em** innerhalb der Kategorie **Glück**. Es besitzt eine **vollständig autarke Ökonomie** (`poker_accounts` & `poker_account_stats`) sowie eine eigene Erfahrungs- und Rang-Kurve (`game_folder = 'poker'`), strikt getrennt von Blackjack. ### 2. Spielregeln & Tischablauf -* **6-Max Tisch (`poker_table.jpg`):** Du spielst gegen **1 bis maximal 5 KI-Gegner** rund um einen dynamisch skalierenden gotischen Pokertisch. +* **6-Max Tisch (`poker_table.png`):** Du spielst gegen **1 bis maximal 5 KI-Gegner** rund um einen dynamisch skalierenden gotischen Pokertisch. * **Einheitlicher Grundeinsatz (Ante) statt asymmetrischer Blinds:** Beim Start einer Hand zahlt jeder aktive Sitz automatisch denselben Grundeinsatz in den Pot (`10 Gold` bei *Klassisch*, `20 Gold` bei *Hoher Einsatz*). Der Dealer-Button `[D]` rotiert jede Runde im Uhrzeigersinn weiter und bestimmt die Zugreihenfolge. * **Setzrunden (Streets):** `Pre-Flop` (2 Hole Cards) $\rightarrow$ `Flop` (3 Gemeinschaftskarten) $\rightarrow$ `Turn` (4. Karte) $\rightarrow$ `River` (5. Karte) $\rightarrow$ `Showdown`. * **No-Limit, All-In & Side-Pots:** Jederzeit **All-In** möglich. Bei unterschiedlich hohen Stacks berechnet die `PokerEngine` automatisch exakte Haupt- und **Side-Pots**. @@ -29,7 +29,7 @@ Das Modul `games/poker/` implementiert **6-Max No-Limit Texas Hold'em** innerhal The `games/poker/` module implements **6-Max No-Limit Texas Hold'em** under the **Luck** category with a **standalone economy** (`poker_accounts`, `poker_account_stats`) and isolated XP progression (`game_folder = 'poker'`). ### 2. Rules & Table Features -* **6-Max Arena (`poker_table.jpg`):** Play against **1 to 5 AI opponents** arranged around a dynamically scaling Gothic poker table. +* **6-Max Arena (`poker_table.png`):** Play against **1 to 5 AI opponents** arranged around a dynamically scaling Gothic poker table. * **Equal Entry Ante:** At the start of each hand, every active seat automatically posts the table's base ante (`10 Gold` in *Classic*, `20 Gold` in *High Stakes*) before starting in **Pre-Flop**, while the Dealer button `[D]` rotates clockwise. * **Streets & Side Pots:** Full `Pre-Flop` $\rightarrow$ `Flop` $\rightarrow$ `Turn` $\rightarrow$ `River` $\rightarrow$ `Showdown` flow with automatic multi-way **Side Pot** resolution on uneven All-Ins. * **Visual Hand Reference & `ⓘ` Tooltips:** Static 2-column mini-card cheat sheet (no hand spoilers during play) paired with hover/click `ⓘ` (`InfoBadge`) explanations for all 10 hand rankings and betting actions. diff --git a/games/poker/views/__pycache__/poker_menu_view.cpython-311.pyc b/games/poker/views/__pycache__/poker_menu_view.cpython-311.pyc index 04b41e7..7a6f4fb 100644 Binary files a/games/poker/views/__pycache__/poker_menu_view.cpython-311.pyc and b/games/poker/views/__pycache__/poker_menu_view.cpython-311.pyc differ diff --git a/games/poker/views/__pycache__/poker_stats_view.cpython-311.pyc b/games/poker/views/__pycache__/poker_stats_view.cpython-311.pyc index 8f7748f..475863a 100644 Binary files a/games/poker/views/__pycache__/poker_stats_view.cpython-311.pyc and b/games/poker/views/__pycache__/poker_stats_view.cpython-311.pyc differ diff --git a/games/poker/views/poker_menu_view.py b/games/poker/views/poker_menu_view.py index e748fc8..aa4e60e 100644 --- a/games/poker/views/poker_menu_view.py +++ b/games/poker/views/poker_menu_view.py @@ -7,7 +7,7 @@ import tkinter as tk from games.poker.views.poker_stats_view import PokerStatsView from games.poker.views.poker_table_view import PokerTableView -from games.solitaire.base.solitaire_menu_chrome import create_menu_body_canvas +from view.widgets.menu_body_canvas import MenuBodyCanvas from models.database import Database from models.progression import Progression from resources.code_res.game_constants import ( @@ -133,7 +133,7 @@ class PokerMenuView: on_lang_refresh=refresh_on_lang_switch, ) - cv = create_menu_body_canvas(self.ctx) + cv = MenuBodyCanvas(self.ctx) 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 @@ -339,7 +339,7 @@ class PokerMenuView: table_buttons.append((v_key, t_btn)) def draw_layout(w: int, h: int): - cv._sync_bg(w, h) # type: ignore[attr-defined] + cv.sync_bg(w, h) cv.delete("fg") self._photo_refs.clear() diff --git a/games/poker/views/poker_stats_view.py b/games/poker/views/poker_stats_view.py index eb66a5f..3da87d0 100644 --- a/games/poker/views/poker_stats_view.py +++ b/games/poker/views/poker_stats_view.py @@ -2,7 +2,6 @@ # games/poker/views/poker_stats_view.py from __future__ import annotations -from games.solitaire.base.solitaire_menu_chrome import create_menu_body_canvas from models.database import Database from resources.code_res.game_constants import ( FONT_COLOR_HEADING_SUB, @@ -10,6 +9,7 @@ from resources.code_res.game_constants import ( ) from resources.code_res.i18n import t from view.widgets.image_button import ImageButton +from view.widgets.menu_body_canvas import MenuBodyCanvas from view.widgets.stats_board_widget import StatsBoardWidget GAME_FOLDER_ID = "poker" @@ -48,13 +48,12 @@ class PokerStatsView: on_lang_refresh=lambda: self.show(active_acc["id"]), ) - cv = create_menu_body_canvas(self.ctx) + cv = MenuBodyCanvas(self.ctx) 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 acc_btns: list[tuple[ImageButton, int]] = [] - btn_w = 186 for acc in accounts: is_sel = (acc["id"] == active_acc["id"]) btn_lbl = f"{acc['account_name']} ({acc['gold']}g)" @@ -65,11 +64,11 @@ class PokerStatsView: btn_fire if is_sel else btn_purp, lambda aid=acc["id"]: self.show(selected_acc_id=aid), sound_mgr=self.ctx.sounds, - width=btn_w, + width=180, height=38, style="fire" if is_sel else "amethyst", ) - acc_btns.append((b, btn_w)) + acc_btns.append((b, b.pixel_width)) pk_variants = Database.get_variants_for_filter(folder_path=GAME_FOLDER_ID) pk_filter_map = {t("pk_filter_all_tables"): None} @@ -84,7 +83,7 @@ class PokerStatsView: ) def draw_layout(w: int, h: int): - cv._sync_bg(w, h) # type: ignore[attr-defined] + cv.sync_bg(w, h) cv.delete("fg") self._photo_refs.clear() diff --git a/games/solitaire/base/__pycache__/solitaire_stats_view.cpython-311.pyc b/games/solitaire/base/__pycache__/solitaire_stats_view.cpython-311.pyc index 3fc0cc5..1b258ec 100644 Binary files a/games/solitaire/base/__pycache__/solitaire_stats_view.cpython-311.pyc and b/games/solitaire/base/__pycache__/solitaire_stats_view.cpython-311.pyc differ diff --git a/games/solitaire/base/solitaire_bottom_bar.py b/games/solitaire/base/solitaire_bottom_bar.py new file mode 100644 index 0000000..c063d46 --- /dev/null +++ b/games/solitaire/base/solitaire_bottom_bar.py @@ -0,0 +1,190 @@ +# -*- coding: utf-8 -*- +# games/solitaire/base/solitaire_bottom_bar.py +from __future__ import annotations + +import tkinter as tk +from PIL import Image, ImageTk + +import resources.code_res.game_constants as gc +from resources.code_res.game_constants import ( + BG_COLOR, + FONT_COLOR_HEADING_SUB, + FONT_SIZE_SMALL_MIN, + UI_ACCENT_AMETHYST, +) +from view.widgets.image_button import ImageButton + +BG_SAFE_SIDE_RATIO = getattr(gc, "BG_SAFE_SIDE_RATIO", 0.088) +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. + """ + + CONTENT_H = 48 + + 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)) + init_h = self.CONTENT_H + self._bottom_inset + + super().__init__( + parent, + height=init_h, + bg=BG_COLOR, + bd=0, + highlightthickness=0, + ) + self.ctx = ctx + self.assets = ctx.assets + self.hud_var = hud_var + self.status_var = status_var + + self._buttons: list[ImageButton] = [] + self._bg_ph: ImageTk.PhotoImage | None = None + self._frame_ph: ImageTk.PhotoImage | None = None + self._txt_refs: list[ImageTk.PhotoImage] = [] + self._btn_left_limit: int = 500 + + self.hud_var.trace_add("write", lambda *_: self.refresh_texts()) + self.status_var.trace_add("write", lambda *_: self.refresh_texts()) + self.bind("", self._on_configure) + + def set_buttons(self, buttons: list[ImageButton]): + self._buttons = list(buttons) + self.relayout() + self.after(20, self.relayout) + + def relayout(self): + if not self.winfo_exists(): + return + w = self.winfo_width() + h = self.winfo_height() + if w >= 120 and h >= 40: + self._slice_bg(w, h) + self._layout(w, h) + + def _slice_bg(self, w: int, h: int): + root = self.ctx.root + rw = max(w, root.winfo_width()) + rh = max(h, root.winfo_height()) + ox = max(0, min(rw - w, self.winfo_rootx() - root.winfo_rootx())) + oy = max(0, min(rh - h, self.winfo_rooty() - root.winfo_rooty())) + + if hasattr(self.assets, "get_bg_patch_photo"): + self._bg_ph = self.assets.get_bg_patch_photo(rw, rh, ox, oy, w, 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 + scaled = src.resize((rw, rh), Image.Resampling.BILINEAR) + self._bg_ph = ImageTk.PhotoImage(scaled.crop((ox, oy, ox + w, oy + h))) + + if self._bg_ph is None: + return + self.delete("bb_bg") + self.create_image(0, 0, image=self._bg_ph, anchor="nw", tags="bb_bg") + self.tag_lower("bb_bg") + + def _on_configure(self, event): + if event.widget is not self: + return + w, h = max(1, event.width), max(1, event.height) + if w < 120: + return + + root_h = max(600, self.ctx.root.winfo_height()) + new_bot = max(52, 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 + self.configure(height=h) + + self._slice_bg(w, h) + self._layout(w, h) + + def refresh_texts(self): + if self.winfo_exists() and self.winfo_width() >= 120: + self._draw_texts(self.winfo_width(), self.winfo_height()) + + def _layout(self, w: int, h: int): + self.delete("bb_frame") + + side_inset = max(92, int(w * BG_SAFE_SIDE_RATIO)) + frame_w = max(240, w - 2 * side_inset) + cy = self.CONTENT_H // 2 + + try: + self._frame_ph = self.assets.get_box_photo( + "box_gold_double", (frame_w, self.CONTENT_H - 2), border_scale=0.85 + ) + except TypeError: + self._frame_ph = self.assets.get_box_photo("box_gold_double", (frame_w, self.CONTENT_H - 2)) + + 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._btn_left_limit = rx + self._draw_texts(w, h) + + def _draw_texts(self, w: int, _h: int): + self.delete("bb_txt") + self._txt_refs.clear() + + 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 + + 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) + 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 + + st_str = (self.status_var.get() or "").replace("•", "-") + if st_str and (right_limit - lx) >= 80: + 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, + align="left", + ) + self._txt_refs.append(st_ph) + self.create_image(lx, cy, image=st_ph, anchor="w", tags="bb_txt") \ No newline at end of file diff --git a/games/solitaire/base/solitaire_menu_chrome.py b/games/solitaire/base/solitaire_menu_chrome.py deleted file mode 100644 index 0e317dc..0000000 --- a/games/solitaire/base/solitaire_menu_chrome.py +++ /dev/null @@ -1,111 +0,0 @@ -# -*- coding: utf-8 -*- -# games/solitaire/base/solitaire_menu_chrome.py -from __future__ import annotations - -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_COLOR_TITLE_MAIN, - FONT_SIZE_BODY, - FONT_SIZE_TITLE_LG, -) -from view.widgets.goth_dropdown import GothDropdown -from view.widgets.image_button import ImageButton - - -def create_menu_body_canvas(ctx, topbar_h: int = 56) -> tk.Canvas: - """Erstellt ein vollflächiges Menü-Canvas unterhalb der GothTopbar, das background_*.jpg nahtlos zeigt.""" - GothDropdown.close_any_open_popup() - cv = tk.Canvas(ctx.root, bg=BG_COLOR, bd=0, highlightthickness=0) - cv.place(x=0, y=topbar_h, relwidth=1.0, relheight=1.0, height=-topbar_h) - - state = {"last": (0, 0), "bg_ph": None} - - def _sync_bg(w: int, h: int): - if (w, h) == state["last"] or w < 80 or h < 80: - return - state["last"] = (w, h) - rw = max(w, ctx.root.winfo_width()) - rh = max(h + topbar_h, ctx.root.winfo_height()) - src = ( - ctx.assets.raw_bg_vertical - if (rh > rw and ctx.assets.raw_bg_vertical is not None) - else (ctx.assets.raw_bg_horizontal or ctx.assets.raw_bg) - ) - if src is None: - return - full_img = src.resize((rw, rh), Image.Resampling.LANCZOS) - cropped = full_img.crop((0, topbar_h, min(rw, w), min(rh, topbar_h + h))) - state["bg_ph"] = ImageTk.PhotoImage(cropped) - cv.delete("menu_bg") - cv.create_image(0, 0, image=state["bg_ph"], anchor="nw", tags="menu_bg") - cv.tag_lower("menu_bg") - - cv._sync_bg = _sync_bg # type: ignore[attr-defined] - return cv - - -def open_goth_modal( - ctx, - title_txt: str, - body_txt: str, - buttons: list[tuple[str, str, object]], - is_danger: bool = False, -) -> tk.Canvas: - """Rahmenloses Gothic-Modal auf background_vertical.jpg + box_big.png für Solitaire-Dialoge.""" - GothDropdown.close_any_open_popup() - dlg_w = 560 if len(buttons) >= 3 else 490 - dlg_h = 265 - - overlay = tk.Canvas( - ctx.root, width=dlg_w, height=dlg_h, bg=BG_COLOR, bd=0, highlightthickness=0 - ) - overlay.place(relx=0.5, rely=0.53, anchor="center") - - refs: list = [] - overlay._goth_refs = refs # type: ignore[attr-defined] - - bg_src = ctx.assets.raw_bg_vertical or ctx.assets.raw_bg_horizontal or ctx.assets.raw_bg - if bg_src is not None: - bg_ph = ImageTk.PhotoImage(bg_src.resize((dlg_w, dlg_h), Image.Resampling.LANCZOS)) - refs.append(bg_ph) - overlay.create_image(0, 0, image=bg_ph, anchor="nw") - - box_ph = ctx.assets.get_box_photo("box_big", (dlg_w - 6, dlg_h - 6)) - if box_ph: - refs.append(box_ph) - overlay.create_image(dlg_w // 2, dlg_h // 2, image=box_ph, anchor="center") - - t_col = FONT_COLOR_STATUS_LOSS if is_danger else FONT_COLOR_TITLE_MAIN - t_ph = ctx.assets.get_goth_text_photo(title_txt, FONT_SIZE_TITLE_LG - 4, t_col, max_width=dlg_w - 60) - b_ph = ctx.assets.get_goth_text_photo( - body_txt, FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, max_width=dlg_w - 72, align="center" - ) - refs.extend([t_ph, b_ph]) - overlay.create_image(dlg_w // 2, 52, image=t_ph, anchor="center") - overlay.create_image(dlg_w // 2, 124, image=b_ph, anchor="center") - - btn_norm = ctx.assets.raw_btn_default - btn_purp = ctx.assets.raw_btn_purple - btn_fire = ctx.assets.raw_btn_fire or btn_purp - - bw = 160 if len(buttons) >= 3 else 182 - gap = 10 - total_w = len(buttons) * bw + max(0, len(buttons) - 1) * gap - cur_x = (dlg_w - total_w) // 2 - - for lbl, style, cmd in buttons: - p_n = btn_fire if style == "fire" else btn_norm - p_h = btn_fire if style == "fire" else btn_purp - b = ImageButton( - overlay, lbl, p_n, p_h, cmd, - sound_mgr=ctx.sounds, width=bw, height=38, style=style - ) - overlay.create_window(cur_x + bw // 2, dlg_h - 46, window=b, anchor="center") - cur_x += bw + gap - - return overlay \ No newline at end of file diff --git a/games/solitaire/base/solitaire_modal_dialog.py b/games/solitaire/base/solitaire_modal_dialog.py new file mode 100644 index 0000000..d7d8a99 --- /dev/null +++ b/games/solitaire/base/solitaire_modal_dialog.py @@ -0,0 +1,144 @@ +# -*- coding: utf-8 -*- +# games/solitaire/base/solitaire_modal_dialog.py +from __future__ import annotations + +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_COLOR_TITLE_MAIN, + FONT_SIZE_BODY, + FONT_SIZE_TITLE_LG, +) +from view.widgets.goth_dropdown import GothDropdown +from view.widgets.image_button import ImageButton + + +class SolitaireModalDialog(tk.Canvas): + """ + Rahmenloses Gothic-Modal auf background_vertical.jpg + box_big.png + für Wiederaufnahme-, Aufgeben-, Deadlock- und Sieg-Dialoge (inkl. win.gif) in Solitaire. + """ + + def __init__( + self, + ctx, + title_txt: str, + body_txt: str, + buttons: list[tuple[str, str, object, bool] | tuple[str, str, object]], + is_danger: bool = False, + gif_key: str = "", + ): + GothDropdown.close_any_open_popup() + frames = ctx.assets.get_gif_frames(gif_key, size=(150, 84)) if gif_key else [] + dlg_w = 590 if len(buttons) >= 3 else 500 + dlg_h = 355 if frames else 268 + + super().__init__( + ctx.root, + width=dlg_w, + height=dlg_h, + bg=BG_COLOR, + bd=0, + highlightthickness=0, + ) + self.ctx = ctx + self._dlg_w = dlg_w + self._dlg_h = dlg_h + self._photo_refs: list[ImageTk.PhotoImage] = [] + self._gif_job: str | None = None + self._gif_item: int | None = None + + self.place(relx=0.5, rely=0.52, anchor="center") + self.bind("", self._on_destroy) + self._build_scene(title_txt, body_txt, buttons, is_danger, frames) + + def _on_destroy(self, event=None): + if event is not None and event.widget is not self: + return + if self._gif_job is not None: + try: + self.after_cancel(self._gif_job) + except Exception: + pass + self._gif_job = None + + def _animate_gif(self, frames: list, idx: int): + if not self.winfo_exists() or self._gif_item is None: + return + self.itemconfigure(self._gif_item, image=frames[idx % len(frames)]) + self._gif_job = self.after(90, self._animate_gif, frames, (idx + 1) % len(frames)) + + def _build_scene( + self, + title_txt: str, + body_txt: str, + buttons: list, + is_danger: bool, + frames: list, + ): + w, h = self._dlg_w, self._dlg_h + assets = self.ctx.assets + + bg_src = assets.raw_bg_vertical or assets.raw_bg_horizontal or assets.raw_bg + if bg_src is not None: + bg_ph = ImageTk.PhotoImage(bg_src.resize((w, h), Image.Resampling.LANCZOS)) + self._photo_refs.append(bg_ph) + self.create_image(0, 0, image=bg_ph, anchor="nw") + + box_ph = assets.get_box_photo("box_big", (w - 6, h - 6)) + if box_ph: + self._photo_refs.append(box_ph) + self.create_image(w // 2, h // 2, image=box_ph, anchor="center") + + cur_y = 26 + if frames: + self._gif_item = self.create_image(w // 2, cur_y + 42, image=frames[0], anchor="center") + cur_y += 92 + if len(frames) > 1: + self._animate_gif(frames, 0) + else: + cur_y = 38 + + t_col = FONT_COLOR_STATUS_LOSS if is_danger else FONT_COLOR_TITLE_MAIN + clean_body = str(body_txt or "").replace("•", "-") + t_ph = assets.get_goth_text_photo(title_txt, FONT_SIZE_TITLE_LG - 4, t_col, max_width=w - 64) + b_ph = assets.get_goth_text_photo( + clean_body, FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, max_width=w - 76, align="center" + ) + self._photo_refs.extend([t_ph, b_ph]) + self.create_image(w // 2, cur_y + t_ph.height() // 2, image=t_ph, anchor="center") + cur_y += t_ph.height() + 14 + self.create_image(w // 2, cur_y + b_ph.height() // 2, image=b_ph, anchor="center") + + btn_norm = assets.raw_btn_default + btn_purp = assets.raw_btn_purple + btn_fire = assets.raw_btn_fire or btn_purp + + req_w = 152 if len(buttons) >= 3 else 176 + gap = 10 + created_btns: list[ImageButton] = [] + for entry in buttons: + if len(entry) == 4: + lbl, style, cmd, enabled = entry + else: + lbl, style, cmd = entry + enabled = True + p_n = btn_fire if style == "fire" else btn_norm + p_h = btn_fire if style == "fire" else btn_purp + btn = ImageButton( + self, lbl, p_n, p_h, cmd, + sound_mgr=self.ctx.sounds, width=req_w, height=36, + enabled=bool(enabled), style=style, + ) + created_btns.append(btn) + + total_w = sum(b.pixel_width for b in created_btns) + max(0, len(created_btns) - 1) * gap + cur_x = (w - total_w) // 2 + for btn in created_btns: + bw = btn.pixel_width + self.create_window(cur_x + bw // 2, h - 44, window=btn, anchor="center") + cur_x += bw + gap \ No newline at end of file diff --git a/games/solitaire/base/solitaire_stats_view.py b/games/solitaire/base/solitaire_stats_view.py index 6ef4c25..dde1af8 100644 --- a/games/solitaire/base/solitaire_stats_view.py +++ b/games/solitaire/base/solitaire_stats_view.py @@ -2,7 +2,7 @@ # games/solitaire/base/solitaire_stats_view.py from __future__ import annotations -from games.solitaire.base.solitaire_menu_chrome import create_menu_body_canvas +from view.widgets.menu_body_canvas import MenuBodyCanvas from models.database import Database from resources.code_res.game_constants import ( FONT_COLOR_BODY_DEFAULT, @@ -58,7 +58,7 @@ class SolitaireStatsView: on_lang_refresh=lambda: self.show(preselect_variant_id=self._active_variant_id), ) - cv = create_menu_body_canvas(self.ctx) + cv = MenuBodyCanvas(self.ctx) 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 @@ -105,7 +105,7 @@ class SolitaireStatsView: ) def draw_layout(w: int, h: int): - cv._sync_bg(w, h) # type: ignore[attr-defined] + cv.sync_bg(w, h) # type: ignore[attr-defined] cv.delete("fg") self._photo_refs.clear() diff --git a/games/solitaire/base/solitaire_theme.py b/games/solitaire/base/solitaire_theme.py index 8d12bd1..9d4a1fc 100644 --- a/games/solitaire/base/solitaire_theme.py +++ b/games/solitaire/base/solitaire_theme.py @@ -169,13 +169,28 @@ class SolitaireTableBgRenderer: ibot = max(26, int(canvas_h * self.FRAME_BOT_RATIO)) return ix, itop, ibot - def draw_on_canvas(self, canvas, canvas_w: int, canvas_h: int): - pil_img = self._ensure_pil() - if pil_img is None or canvas_w < 50 or canvas_h < 50: + def draw_on_canvas(self, canvas: tk.Canvas, canvas_w: int, canvas_h: int): + if canvas_w < 80 or canvas_h < 80: return - target_sz = (canvas_w, canvas_h) - if self._cached_photo is None or self._cached_size != target_sz: - scaled = pil_img.resize(target_sz, Image.Resampling.BILINEAR) - self._cached_photo = ImageTk.PhotoImage(scaled) - self._cached_size = target_sz - canvas.create_image(0, 0, image=self._cached_photo, anchor="nw", tags=("table_bg",)) \ No newline at end of file + root = canvas.winfo_toplevel() + assets = getattr(root, "assets", None) + if assets is None: + return + + rw = max(canvas_w, root.winfo_width()) + rh = max(canvas_h, root.winfo_height()) + ox = max(0, min(rw - canvas_w, canvas.winfo_rootx() - root.winfo_rootx())) + oy = max(0, min(rh - canvas_h, canvas.winfo_rooty() - root.winfo_rooty())) + new_photo = assets.get_bg_patch_photo(rw, rh, ox, oy, canvas_w, canvas_h) + if new_photo is None: + return + + existing = canvas.find_withtag("table_bg_slice") + if existing: + if new_photo is not self._slice_photo: + self._slice_photo = new_photo + canvas.itemconfigure(existing[0], image=self._slice_photo) + else: + self._slice_photo = new_photo + canvas.create_image(0, 0, image=self._slice_photo, anchor="nw", tags=("table_bg_slice",)) + canvas.tag_lower("table_bg_slice") \ No newline at end of file diff --git a/games/solitaire/base/solitaire_victory_dialog.py b/games/solitaire/base/solitaire_victory_dialog.py new file mode 100644 index 0000000..1c1448f --- /dev/null +++ b/games/solitaire/base/solitaire_victory_dialog.py @@ -0,0 +1,178 @@ +# -*- coding: utf-8 -*- +# games/solitaire/base/solitaire_victory_dialog.py +from __future__ import annotations + +import tkinter as tk +from PIL import Image, ImageTk + +from models.database import Database +from models.progression import Progression +from resources.code_res.game_constants import ( + BG_COLOR, + FONT_COLOR_BODY_DEFAULT, + FONT_COLOR_HEADING_SUB, + FONT_COLOR_STATUS_WIN, + FONT_COLOR_TITLE_MAIN, + FONT_SIZE_BODY, + FONT_SIZE_HEADING, + FONT_SIZE_TITLE_LG, +) +from resources.code_res.i18n import t +from view.widgets.goth_dropdown import GothDropdown +from view.widgets.image_button import ImageButton + + +class SolitaireVictoryDialog(tk.Canvas): + """ + Rahmenloses Gothic-Sieg-Overlay für Solitaire auf background_vertical.jpg + box_big.png + mit animiertem win_gif und PIL-Old-London-Typografie. + """ + + DLG_W = 500 + DLG_H = 365 + + def __init__( + self, + ctx, + score: int, + moves: int, + dur: float, + difficulty: int, + xp_earned: int, + old_lvl: int, + new_lvl: int, + on_play_again, + on_to_menu, + ): + GothDropdown.close_any_open_popup() + super().__init__( + ctx.root, + width=self.DLG_W, + height=self.DLG_H, + bg=BG_COLOR, + bd=0, + highlightthickness=0, + ) + self.ctx = ctx + self._photo_refs: list[ImageTk.PhotoImage] = [] + self._gif_job: str | None = None + self._gif_item: int | None = None + + self.place(relx=0.5, rely=0.52, anchor="center") + self.bind("", self._on_destroy) + self._build_scene( + score, moves, dur, difficulty, xp_earned, old_lvl, new_lvl, on_play_again, on_to_menu + ) + + def _on_destroy(self, _event=None): + if self._gif_job is not None: + try: + self.after_cancel(self._gif_job) + except Exception: + pass + self._gif_job = None + + def _build_scene( + self, + score: int, + moves: int, + dur: float, + difficulty: int, + xp_earned: int, + old_lvl: int, + new_lvl: int, + on_play_again, + on_to_menu, + ): + w, h = self.DLG_W, self.DLG_H + cx = w // 2 + assets = self.ctx.assets + + bg_src = assets.raw_bg_vertical or assets.raw_bg_horizontal or assets.raw_bg + if bg_src is not None: + bg_ph = ImageTk.PhotoImage(bg_src.resize((w, h), Image.Resampling.LANCZOS)) + self._photo_refs.append(bg_ph) + self.create_image(0, 0, image=bg_ph, anchor="nw") + + box_ph = assets.get_box_photo("box_big", (w - 6, h - 6)) + if box_ph: + self._photo_refs.append(box_ph) + self.create_image(cx, h // 2, image=box_ph, anchor="center") + + cur_y = 26 + frames = assets.get_gif_frames("win_gif", size=(155, 86)) + if frames: + self._gif_item = self.create_image(cx, cur_y + 43, image=frames[0], anchor="center") + cur_y += 96 + if len(frames) > 1: + self._step_gif(frames, 0) + else: + cur_y += 18 + + t_ph = assets.get_goth_text_photo( + t("sol_win_title"), FONT_SIZE_TITLE_LG - 2, FONT_COLOR_TITLE_MAIN, max_width=w - 60 + ) + self._photo_refs.append(t_ph) + self.create_image(cx, cur_y + t_ph.height() // 2, image=t_ph, anchor="center") + cur_y += t_ph.height() + 10 + + sum_txt = t( + "sol_win_summary", + score, + moves, + Database.format_seconds(dur), + t(f"sol_diff_short_{difficulty}"), + ).replace("•", "-") + s_ph = assets.get_goth_text_photo( + sum_txt, FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, max_width=w - 68 + ) + self._photo_refs.append(s_ph) + self.create_image(cx, cur_y + s_ph.height() // 2, image=s_ph, anchor="center") + cur_y += s_ph.height() + 10 + + xp_ph = assets.get_goth_text_photo( + t("bj_popup_xp_earned", xp_earned), FONT_SIZE_HEADING - 3, FONT_COLOR_HEADING_SUB, max_width=w - 68 + ) + self._photo_refs.append(xp_ph) + self.create_image(cx, cur_y + xp_ph.height() // 2, image=xp_ph, anchor="center") + cur_y += xp_ph.height() + 8 + + if new_lvl > old_lvl: + lvl_ph = assets.get_goth_text_photo( + t("bj_popup_level_up", new_lvl, Progression.get_prestige_title(new_lvl)), + FONT_SIZE_BODY + 1, + FONT_COLOR_STATUS_WIN, + max_width=w - 64, + ) + self._photo_refs.append(lvl_ph) + self.create_image(cx, cur_y + lvl_ph.height() // 2, image=lvl_ph, anchor="center") + + btn_norm = assets.raw_btn_default + btn_purp = assets.raw_btn_purple + btn_fire = assets.raw_btn_fire or btn_purp + + b_again = ImageButton( + self, t("sol_play_again_btn"), btn_fire, btn_fire, + on_play_again, sound_mgr=self.ctx.sounds, width=178, height=38, style="fire" + ) + b_menu = ImageButton( + self, t("bj_popup_to_menu_btn"), btn_norm, btn_purp, + on_to_menu, sound_mgr=self.ctx.sounds, width=178, height=38, style="amethyst" + ) + + gap = 12 + tot_w = b_again.pixel_width + b_menu.pixel_width + gap + sx = (w - tot_w) // 2 + self.create_window(sx + b_again.pixel_width // 2, h - 44, window=b_again, anchor="center") + self.create_window( + sx + b_again.pixel_width + gap + b_menu.pixel_width // 2, + h - 44, + window=b_menu, + anchor="center", + ) + + def _step_gif(self, frames: list, idx: int): + if not self.winfo_exists() or self._gif_item is None: + return + self.itemconfigure(self._gif_item, image=frames[idx % len(frames)]) + self._gif_job = self.after(90, self._step_gif, frames, (idx + 1) % len(frames)) \ No newline at end of file diff --git a/games/solitaire/freecell/views/__pycache__/freecell_menu_view.cpython-311.pyc b/games/solitaire/freecell/views/__pycache__/freecell_menu_view.cpython-311.pyc index 7eea225..8b3abbf 100644 Binary files a/games/solitaire/freecell/views/__pycache__/freecell_menu_view.cpython-311.pyc and b/games/solitaire/freecell/views/__pycache__/freecell_menu_view.cpython-311.pyc differ diff --git a/games/solitaire/freecell/views/__pycache__/freecell_table_view.cpython-311.pyc b/games/solitaire/freecell/views/__pycache__/freecell_table_view.cpython-311.pyc index 712db68..b4d1274 100644 Binary files a/games/solitaire/freecell/views/__pycache__/freecell_table_view.cpython-311.pyc and b/games/solitaire/freecell/views/__pycache__/freecell_table_view.cpython-311.pyc differ diff --git a/games/solitaire/freecell/views/freecell_menu_view.py b/games/solitaire/freecell/views/freecell_menu_view.py index 1e34b79..2e4f3d9 100644 --- a/games/solitaire/freecell/views/freecell_menu_view.py +++ b/games/solitaire/freecell/views/freecell_menu_view.py @@ -5,7 +5,7 @@ from __future__ import annotations import json import tkinter as tk -from games.solitaire.base.solitaire_menu_chrome import create_menu_body_canvas, open_goth_modal +from games.solitaire.base.solitaire_modal_dialog import SolitaireModalDialog from games.solitaire.base.solitaire_stats_view import SolitaireStatsView from games.solitaire.freecell.views.freecell_table_view import FreeCellTableView from models.database import Database @@ -28,6 +28,7 @@ from resources.code_res.game_constants import ( from resources.code_res.i18n import t from view.widgets.goth_dropdown import GothDropdown from view.widgets.image_button import ImageButton +from view.widgets.menu_body_canvas import MenuBodyCanvas GAME_FOLDER_ID = "solitaire/freecell" GAME_TITLE_KEY = "game_title_freecell" @@ -66,7 +67,7 @@ class FreeCellMenuView: self.ctx.sounds.play_menu_music() self.ctx.root.clear_window(apply_global_bg=True) self._photo_refs.clear() - prog = self.ctx.refresh_game_progress() + self.ctx.refresh_game_progress() diff_setting_key = f"freecell_diff_{pid}" saved_diff_str = Database.load_setting(diff_setting_key, "1") @@ -85,18 +86,17 @@ class FreeCellMenuView: on_back=lambda: self.show(), ).show() - rank_badge = f"{prog['title']} (Lv. {prog['level']} • {prog['current_xp']}/{prog['needed_xp']} XP)" self.ctx.build_game_topbar( self.ctx.root, t("fc_menu_topbar"), on_game_menu=None, on_stats=open_stats, stats_enabled=True, - extra_right_text=rank_badge, + extra_right_text="", on_lang_refresh=lambda: self.show(status_msg=status_msg, status_is_ok=status_is_ok), ) - cv = create_menu_body_canvas(self.ctx) + cv = MenuBodyCanvas(self.ctx) btn_fire = self.ctx.assets.raw_btn_fire or self.ctx.assets.raw_btn_purple saved = Database.load_game_state(pid, GAME_FOLDER_ID) @@ -105,9 +105,15 @@ class FreeCellMenuView: resume_btn = None if saved and saved_meta is not None: resume_btn = ImageButton( - cv, t("sol_resume_btn"), btn_fire, btn_fire, + cv, + t("sol_resume_btn"), + btn_fire, + btn_fire, lambda: self._resume_saved(saved, saved_meta["difficulty"]), - sound_mgr=self.ctx.sounds, width=190, height=38, style="fire", + sound_mgr=self.ctx.sounds, + width=180, + height=38, + style="fire", ) diff_labels = [t(f"sol_diff_{lvl}") for lvl in sorted(SOLITAIRE_DIFFICULTIES.keys())] @@ -126,15 +132,21 @@ class FreeCellMenuView: ) start_btn = ImageButton( - cv, t("sol_start_btn"), btn_fire, btn_fire, + cv, + t("sol_start_btn"), + btn_fire, + btn_fire, lambda: self._on_start_clicked( DEFAULT_VARIANT_KEY, diff_map.get(diff_var.get(), 1), saved, saved_meta ), - sound_mgr=self.ctx.sounds, width=215, height=40, style="fire", + sound_mgr=self.ctx.sounds, + width=205, + height=40, + style="fire", ) def draw_layout(w: int, h: int): - cv._sync_bg(w, h) # type: ignore[attr-defined] + cv.sync_bg(w, h) cv.delete("fg") self._photo_refs.clear() @@ -144,7 +156,9 @@ class FreeCellMenuView: cur_y = max(26, int(h * 0.06)) - title_ph = self.ctx.assets.get_goth_text_photo(t(GAME_TITLE_KEY), FONT_SIZE_TITLE_LG, FONT_COLOR_TITLE_MAIN, align="left") + title_ph = self.ctx.assets.get_goth_text_photo( + t(GAME_TITLE_KEY), FONT_SIZE_TITLE_LG, FONT_COLOR_TITLE_MAIN, align="left" + ) sub_ph = self.ctx.assets.get_goth_text_photo( t("fc_menu_subtitle"), FONT_SIZE_BODY, FONT_COLOR_BODY_MUTED, max_width=box_w, align="left" ) @@ -156,9 +170,11 @@ class FreeCellMenuView: if status_msg: st_ph = self.ctx.assets.get_goth_text_photo( - status_msg, FONT_SIZE_BODY, + status_msg, + FONT_SIZE_BODY, FONT_COLOR_STATUS_WIN if status_is_ok else FONT_COLOR_STATUS_LOSS, - max_width=box_w, align="left", + max_width=box_w, + align="left", ) self._photo_refs.append(st_ph) cv.create_image(x_left, cur_y, image=st_ph, anchor="nw", tags="fg") @@ -184,7 +200,10 @@ class FreeCellMenuView: saved_meta["score"], Database.format_seconds(saved_meta["elapsed_sec"]), ), - FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, max_width=box_w - 250, align="left", + FONT_SIZE_BODY, + FONT_COLOR_BODY_DEFAULT, + max_width=box_w - resume_btn.pixel_width - 70, + align="left", ) self._photo_refs.extend([rt_ph, ri_ph]) cv.create_image(x_left + 26, res_cy - 17, image=rt_ph, anchor="w", tags="fg") @@ -199,7 +218,7 @@ class FreeCellMenuView: cv.create_image(x_left + 6, cur_y, image=sec_ph, anchor="nw", tags="fg") cur_y += sec_ph.height() + 8 - setup_h = 205 + setup_h = 208 setup_cy = cur_y + setup_h // 2 s_box = self.ctx.assets.get_box_photo("box_big", (box_w, setup_h)) if s_box: @@ -211,11 +230,18 @@ class FreeCellMenuView: # Zeile 1: Modus r1_y = cur_y + 44 - m_lbl = self.ctx.assets.get_goth_text_photo(t("fc_variant_info_lbl"), FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, align="left") - m_val = self.ctx.assets.get_goth_text_photo(t("variant_freecell_std"), FONT_SIZE_HEADING - 3, FONT_COLOR_TITLE_MAIN, align="left") + m_lbl = self.ctx.assets.get_goth_text_photo( + t("fc_variant_info_lbl"), FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, align="left" + ) + m_val = self.ctx.assets.get_goth_text_photo( + t("variant_freecell_std"), FONT_SIZE_HEADING - 3, FONT_COLOR_TITLE_MAIN, align="left" + ) m_dsc = self.ctx.assets.get_goth_text_photo( - t("fc_desc_freecell_std"), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, - max_width=max(200, box_w - 260 - m_val.width()), align="left", + t("fc_desc_freecell_std"), + FONT_SIZE_SMALL_MIN, + FONT_COLOR_BODY_MUTED, + max_width=max(180, box_w - 275 - m_val.width()), + align="left", ) self._photo_refs.extend([m_lbl, m_val, m_dsc]) cv.create_image(lbl_col, r1_y, image=m_lbl, anchor="w", tags="fg") @@ -223,12 +249,14 @@ class FreeCellMenuView: cv.create_image(val_col + m_val.width() + 18, r1_y, image=m_dsc, anchor="w", tags="fg") # Zeile 2: Schwierigkeitsgrad - r2_y = cur_y + 102 - d_lbl = self.ctx.assets.get_goth_text_photo(t("sol_diff_lbl"), FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, align="left") + r2_y = cur_y + 104 + d_lbl = self.ctx.assets.get_goth_text_photo( + t("sol_diff_lbl"), FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, align="left" + ) self._photo_refs.append(d_lbl) cv.create_image(lbl_col, r2_y, image=d_lbl, anchor="w", tags="fg") - dd_w = max(240, box_w - 260) + dd_w = max(240, box_w - 265) if diff_dd._width != dd_w: diff_dd._width = dd_w diff_dd.configure(width=dd_w) @@ -291,7 +319,7 @@ class FreeCellMenuView: saved_meta["score"], Database.format_seconds(saved_meta["elapsed_sec"]), ) - self._modal_overlay = open_goth_modal( + self._modal_overlay = SolitaireModalDialog( self.ctx, title_txt=t("sol_resume_box_title"), body_txt=info_txt, @@ -351,7 +379,7 @@ class FreeCellMenuView: self._clear_modal() self._launch_fresh_game(new_variant_key, new_difficulty) - self._modal_overlay = open_goth_modal( + self._modal_overlay = SolitaireModalDialog( self.ctx, title_txt=t("sol_forfeit_title"), body_txt=t("sol_forfeit_desc", penalty), diff --git a/games/solitaire/freecell/views/freecell_table_view.py b/games/solitaire/freecell/views/freecell_table_view.py index 1a0ae4f..f770175 100644 --- a/games/solitaire/freecell/views/freecell_table_view.py +++ b/games/solitaire/freecell/views/freecell_table_view.py @@ -6,8 +6,11 @@ import time import tkinter as tk from games.solitaire.base.card_animator import CardFlightAnimator +from games.solitaire.base.solitaire_bottom_bar import SolitaireBottomBar from games.solitaire.base.solitaire_core import SolitaireCard +from games.solitaire.base.solitaire_modal_dialog import SolitaireModalDialog from games.solitaire.base.solitaire_stats_view import SolitaireStatsView +from games.solitaire.base.solitaire_theme import SolitaireTableBgRenderer from games.solitaire.freecell.models.freecell_engine import FreeCellEngine from models.database import Database from models.progression import Progression @@ -17,12 +20,10 @@ from resources.code_res.game_constants import ( BG_COLOR, BORDER_COLOR, CELL_BG, - ERROR_FG, - FG_COLOR, + FONT_COLOR_TITLE_MAIN, + FONT_SIZE_BODY, FREECELL_VARIANTS, - MODAL_BG, MUTED_FG, - PANEL_BG, PLAYING_CARD_SIZE, RED_SUITS, SOLITAIRE_DIFFICULTIES, @@ -34,7 +35,6 @@ from resources.code_res.game_constants import ( ) from resources.code_res.i18n import t from view.widgets.image_button import ImageButton -from games.solitaire.base.solitaire_theme import SolitaireTableBgRenderer GAME_FOLDER_ID = "solitaire/freecell" GAME_TITLE_KEY = "game_title_freecell" @@ -84,12 +84,12 @@ class FreeCellTableView: self._hint_job: str | None = None self._auto_job: str | None = None self._resize_job: str | None = None - self._gif_job: str | None = None self._bind_ids: list[tuple[str, str]] = [] self._auto_running = False self.animator: CardFlightAnimator | None = None self._bg_renderer = SolitaireTableBgRenderer(self.ctx.assets.res) self._frame_bot_pad: int = 18 + self._canvas_ui_refs: list = [] self._card_aspect: float | None = None self.card_size: tuple[int, int] = PLAYING_CARD_SIZE @@ -106,7 +106,7 @@ class FreeCellTableView: self._last_click_ts: float = 0.0 self._last_click_target: tuple | None = None self._active_hint: dict | None = None - self._modal_overlay: tk.Frame | None = None + self._modal_overlay: tk.Widget | None = None self._build_ui() if not resume_state_json: @@ -120,9 +120,6 @@ class FreeCellTableView: d_mult = SOLITAIRE_DIFFICULTIES.get(self.difficulty, SOLITAIRE_DIFFICULTIES[1])["xp_mult"] return self.cfg["xp_mult"] * d_mult - # ========================================================================= - # UI-Aufbau, Fokus-Überwachung, Exit-Save & Lifecycle - # ========================================================================= def _canvas_alive(self) -> bool: if not self._alive: return False @@ -172,14 +169,13 @@ class FreeCellTableView: self._hint_job, self._auto_job, self._resize_job, - self._gif_job, ): if job is not None: try: self.ctx.root.after_cancel(job) except Exception: pass - self._tick_job = self._focus_job = self._hint_job = self._auto_job = self._resize_job = self._gif_job = None + self._tick_job = self._focus_job = self._hint_job = self._auto_job = self._resize_job = None for seq, func_id in self._bind_ids: try: @@ -216,7 +212,6 @@ class FreeCellTableView: self._window_active = has_focus if should_run: - # Läuft nur weiter, falls der Spieler die Partie bereits durch eine Aktion gestartet hat self.engine.resume_timer() else: if not prev_paused: @@ -230,13 +225,12 @@ class FreeCellTableView: def _build_ui(self): self._play_table_music() - self.ctx.root.clear_window(apply_global_bg=False) - self.ctx.root.configure(bg=BG_COLOR) + self.ctx.root.clear_window(apply_global_bg=True) self.ctx.refresh_game_progress() self.topbar = self.ctx.build_game_topbar( self.ctx.root, - f"{t(f'variant_{self.variant_key}')} • {t(f'sol_diff_short_{self.difficulty}')}", + t(GAME_TITLE_KEY), on_game_menu=self._back_to_game_menu, on_stats=self._open_stats, stats_enabled=True, @@ -244,113 +238,49 @@ class FreeCellTableView: on_lang_refresh=self._refresh_lang, ) - ctrl_bar = tk.Frame( - self.ctx.root, - bg=PANEL_BG, - padx=14, - pady=8, - highlightthickness=1, - highlightbackground=BORDER_COLOR, - ) - ctrl_bar.pack(fill="x", padx=14, pady=(6, 4)) - self.hud_var = tk.StringVar(value="") - tk.Label( - ctrl_bar, - textvariable=self.hud_var, - font=("Georgia", 11, "bold"), - fg=ACCENT_GOLD, - bg=PANEL_BG, - ).pack(side="left") - self.status_var = tk.StringVar(value="") - tk.Label( - ctrl_bar, - textvariable=self.status_var, - font=("Helvetica", 9, "bold"), - fg=ACCENT_GOTH, - bg=PANEL_BG, - ).pack(side="left", padx=(14, 0)) - btn_box = tk.Frame(ctrl_bar, bg=PANEL_BG) - btn_box.pack(side="right") + # Untere Gothic-Leiste mit box_gold_double Rahmen unter dem Spielfeld + self.bottom_bar = SolitaireBottomBar(self.ctx.root, self.ctx, self.hud_var, self.status_var) + self.bottom_bar.pack(fill="x", side="bottom", padx=14, pady=(4, 10)) + + 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.undo_btn = ImageButton( - btn_box, - t("sol_btn_undo"), - self.ctx.assets.raw_sel, - self.ctx.assets.raw_sel_active, - self._on_undo, - sound_mgr=self.ctx.sounds, - width=152, - height=32, - font=("Helvetica", 9, "bold"), - enabled=self.engine.can_undo, + self.bottom_bar, t("sol_btn_undo"), btn_norm, btn_purp, + self._on_undo, sound_mgr=self.ctx.sounds, width=136, height=32, + enabled=self.engine.can_undo, style="amethyst", ) - self.undo_btn.pack(side="left", padx=3) - self.undo_all_btn = ImageButton( - btn_box, - t("sol_btn_undo_all"), - self.ctx.assets.raw_sel, - self.ctx.assets.raw_sel_active, - self._on_undo_all, - sound_mgr=self.ctx.sounds, - width=105, - height=32, - font=("Helvetica", 9, "bold"), - enabled=self.engine.can_undo_all, + self.bottom_bar, t("sol_btn_undo_all"), btn_norm, btn_purp, + self._on_undo_all, sound_mgr=self.ctx.sounds, width=92, height=32, + enabled=self.engine.can_undo_all, style="amethyst", ) - self.undo_all_btn.pack(side="left", padx=3) - self.hint_btn = ImageButton( - btn_box, - t("sol_btn_hint"), - self.ctx.assets.raw_sel, - self.ctx.assets.raw_sel_active, - self._on_hint, - sound_mgr=self.ctx.sounds, - width=102, - height=32, - font=("Helvetica", 9, "bold"), - enabled=not self.engine.won, + self.bottom_bar, t("sol_btn_hint"), btn_norm, btn_purp, + self._on_hint, sound_mgr=self.ctx.sounds, width=92, height=32, + enabled=not self.engine.won, style="amethyst", ) - self.hint_btn.pack(side="left", padx=3) - self.auto_btn = ImageButton( - btn_box, - t("sol_btn_autocomplete"), - self.ctx.assets.raw_btn, - self.ctx.assets.raw_btn_active, - self._start_auto_complete, - sound_mgr=self.ctx.sounds, - width=122, - height=32, - font=("Helvetica", 9, "bold"), - enabled=self.engine.can_auto_complete(), + self.bottom_bar, t("sol_btn_autocomplete"), btn_fire, btn_fire, + self._start_auto_complete, sound_mgr=self.ctx.sounds, width=112, height=32, + enabled=self.engine.can_auto_complete(), style="fire", ) - self.auto_btn.pack(side="left", padx=3) - self.new_btn = ImageButton( - btn_box, + self.bottom_bar, t("sol_btn_forfeit") if self.engine.moves > 0 else t("sol_btn_new_deal"), - self.ctx.assets.raw_sel, - self.ctx.assets.raw_sel_active, - self._on_new_or_forfeit_clicked, - sound_mgr=self.ctx.sounds, - width=112, - height=32, - font=("Helvetica", 9, "bold"), + btn_norm, btn_purp, self._on_new_or_forfeit_clicked, + sound_mgr=self.ctx.sounds, width=104, height=32, style="amethyst", ) - self.new_btn.pack(side="left", padx=(3, 0)) + self.bottom_bar.set_buttons([ + self.undo_btn, self.undo_all_btn, self.hint_btn, self.auto_btn, self.new_btn + ]) - self.canvas = tk.Canvas( - self.ctx.root, - bg=TABLE_BG, - highlightthickness=1, - highlightbackground=SUBTLE_BORDER, - ) - self.canvas.pack(fill="both", expand=True, padx=14, pady=(2, 12)) + self.canvas = tk.Canvas(self.ctx.root, bg=TABLE_BG, bd=0, highlightthickness=0) + self.canvas.pack(fill="both", expand=True, padx=14, pady=(4, 2)) self.animator = CardFlightAnimator(self.ctx.root, self.canvas) self.canvas.bind("", self._on_canvas_configure) @@ -451,9 +381,6 @@ class FreeCellTableView: return Database.save_game_state(pid, GAME_FOLDER_ID, self.variant_key, self.engine.to_json()) - # ========================================================================= - # Uhr, stiller Zeit-Checkpoint & HUD - # ========================================================================= def _start_clock(self): if not self._canvas_alive(): return @@ -478,9 +405,10 @@ class FreeCellTableView: elapsed_str = Database.format_seconds(self.engine.get_elapsed_seconds()) paused_tag = t("sol_hud_paused_tag") if (self.engine.is_timer_paused and not self.engine.won) else "" diff_label = t(f"sol_diff_short_{self.difficulty}") - base_txt = t("sol_hud_stats", self.engine.score, self.engine.moves, elapsed_str, paused_tag, diff_label) - cap_txt = t("fc_hud_capacity", self.engine.max_movable_cards(target_is_empty_tableau=False)) - self.hud_var.set(base_txt + cap_txt) + new_hud = t("sol_hud_stats", self.engine.score, self.engine.moves, elapsed_str, paused_tag, diff_label) + # Nur schreiben, wenn sich der Text tatsächlich geändert hat! + if self.hud_var.get() != new_hud: + self.hud_var.set(new_hud) except Exception: pass @@ -494,18 +422,12 @@ class FreeCellTableView: self.auto_btn.set_enabled((not locked) and self.engine.can_auto_complete()) self.new_btn.set_enabled(not self._auto_running) new_lbl = t("sol_btn_forfeit") if (self.engine.moves > 0 and not self.engine.won) else t("sol_btn_new_deal") - if hasattr(self.new_btn, "set_text"): - self.new_btn.set_text(new_lbl) - elif hasattr(self.new_btn, "configure"): - try: - self.new_btn.configure(text=new_lbl) - except Exception: - pass + prev_w = self.new_btn.pixel_width + self.new_btn.set_text(new_lbl) + if self.new_btn.pixel_width != prev_w: + self.bottom_bar.relayout() self._update_hud_text() - # ========================================================================= - # Kartenpositions-Berechnung & Animations-Helfer - # ========================================================================= @staticmethod def _card_key(card: SolitaireCard) -> tuple[str, str, int]: return (card.suit, card.rank, card.deck_id) @@ -613,9 +535,6 @@ class FreeCellTableView: self.animator.start(flights, self._draw_card_at, duration_ms=duration_ms, on_done=finish) return True - # ========================================================================= - # Ausgewogenes 8-Spalten-Layout & Rendering - # ========================================================================= def _on_canvas_configure(self, _event=None): if not self._canvas_alive(): return @@ -743,7 +662,11 @@ class FreeCellTableView: ): if not self._canvas_alive(): return - self.canvas.delete("all") + bg_ids = set(self.canvas.find_withtag("table_bg_slice")) + for item_id in self.canvas.find_all(): + if item_id not in bg_ids: + self.canvas.delete(item_id) + self._canvas_ui_refs.clear() cw, ch = self.card_size canvas_w = max(680, self.canvas.winfo_width()) canvas_h = max(420, self.canvas.winfo_height()) @@ -846,35 +769,26 @@ class FreeCellTableView: next_y = ys[c_idx + 1] if not is_last else (cur_y + ch) self._tableau_card_rects[col_idx].append((tx, cur_y, tx + cw, next_y)) - # Pause-Banner nur anzeigen, wenn der Timer bereits aktiv gestartet wurde + # Pause-Banner mit box_purple + Old London statt Standard-Rechteck if ( self.engine.has_timer_started and not self._window_active and not self.engine.won and self._modal_overlay is None ): - bw, bh = 430, 42 - bx = (canvas_w - bw) // 2 - by = canvas_h - bh - 12 - self.canvas.create_rectangle( - bx, by, bx + bw, by + bh, - fill=MODAL_BG, - outline=ACCENT_GOTH, - width=2, - ) - self.canvas.create_text( - bx + bw // 2, - by + bh // 2, - text=t("sol_canvas_paused_banner"), - font=("Helvetica", 10, "bold"), - fill=ACCENT_GOLD, + p_ph = self.ctx.assets.get_goth_text_photo( + t("sol_canvas_paused_banner"), FONT_SIZE_BODY, FONT_COLOR_TITLE_MAIN ) + bw, bh = p_ph.width() + 56, max(44, p_ph.height() + 18) + box_ph = self.ctx.assets.get_box_photo("box_purple", (bw, bh)) + self._canvas_ui_refs.extend([p_ph, box_ph] if box_ph else [p_ph]) + pcx, pcy = canvas_w // 2, canvas_h - bh // 2 - 18 + if box_ph: + self.canvas.create_image(pcx, pcy, image=box_ph, anchor="center") + self.canvas.create_image(pcx, pcy, image=p_ph, anchor="center") self._sync_buttons() - # ========================================================================= - # Hit-Testing & Maus-Steuerung (Timer startet erst bei echtem Treffer!) - # ========================================================================= def _hit_test(self, x: int, y: int) -> dict | None: cw, ch = self.card_size @@ -936,7 +850,6 @@ class FreeCellTableView: self._dragging = False if not hit: return - # Erste echte Karteninteraktion -> jetzt startet die Spielzeit! self.engine.start_timer_if_needed() self._update_hud_text() hit["start_xy"] = (event.x, event.y) @@ -1163,9 +1076,6 @@ class FreeCellTableView: return False - # ========================================================================= - # Aktionen: Undo, Undo All, Deadlock-Check, Auto-Complete, Aufgeben & Sieg - # ========================================================================= def _after_player_move(self): self.status_var.set("") self._checkpoint_ticks = 0 @@ -1324,7 +1234,7 @@ class FreeCellTableView: ) updated = Database.adjust_game_points(pid, GAME_FOLDER_ID, -penalty, min_floor_xp=floor_xp) deducted = max(0, prog["total_points"] - updated["total_points"]) - self.ctx.refresh_game_progress() + self.topbar.level_label.configure(text="") self.ctx.sounds.play("lose") if self._modal_overlay is not None: @@ -1349,39 +1259,6 @@ class FreeCellTableView: self._save_progress() penalty = self._compute_forfeit_penalty() - overlay = tk.Frame( - self.ctx.root, - bg=MODAL_BG, - padx=28, - pady=22, - highlightthickness=2, - highlightbackground=ACCENT_GOTH, - ) - overlay.place(relx=0.5, rely=0.52, anchor="center") - self._modal_overlay = overlay - self._sync_buttons() - - tk.Label( - overlay, - text=t("sol_deadlock_title"), - font=("Georgia", 15, "bold"), - fg=ERROR_FG, - bg=MODAL_BG, - ).pack(pady=(0, 8)) - - tk.Label( - overlay, - text=t("sol_deadlock_desc", penalty), - font=("Helvetica", 10), - fg=FG_COLOR, - bg=MODAL_BG, - wraplength=460, - justify="center", - ).pack(pady=(0, 18)) - - row = tk.Frame(overlay, bg=MODAL_BG) - row.pack() - def undo_step(): self._close_active_modal() self._on_undo() @@ -1390,117 +1267,37 @@ class FreeCellTableView: self._close_active_modal() self._on_undo_all() - ImageButton( - row, - t("sol_deadlock_btn_undo"), - self.ctx.assets.raw_btn, - self.ctx.assets.raw_btn_active, - undo_step, - sound_mgr=self.ctx.sounds, - width=170, - height=36, - font=("Helvetica", 9, "bold"), - enabled=self.engine.can_undo, - ).pack(side="left", padx=5) - - ImageButton( - row, - t("sol_deadlock_btn_undo_all"), - self.ctx.assets.raw_btn, - self.ctx.assets.raw_btn_active, - undo_everything, - sound_mgr=self.ctx.sounds, - width=175, - height=36, - font=("Helvetica", 9, "bold"), - enabled=self.engine.can_undo_all, - ).pack(side="left", padx=5) - - ImageButton( - row, - t("sol_deadlock_btn_end", penalty), - self.ctx.assets.raw_sel, - self.ctx.assets.raw_sel_active, - lambda: self._execute_forfeit(penalty, go_menu=True), - sound_mgr=self.ctx.sounds, - width=165, - height=36, - font=("Helvetica", 9, "bold"), - ).pack(side="left", padx=5) + self._modal_overlay = SolitaireModalDialog( + self.ctx, + title_txt=t("sol_deadlock_title"), + body_txt=t("sol_deadlock_desc", penalty), + is_danger=True, + buttons=[ + (t("sol_deadlock_btn_undo"), "fire", undo_step, self.engine.can_undo), + (t("sol_deadlock_btn_undo_all"), "fire", undo_everything, self.engine.can_undo_all), + (t("sol_deadlock_btn_end", penalty), "amethyst", lambda: self._execute_forfeit(penalty, go_menu=True), True), + ], + ) + self._sync_buttons() def _show_forfeit_modal(self): self.engine.pause_timer() self._save_progress() penalty = self._compute_forfeit_penalty() - overlay = tk.Frame( - self.ctx.root, - bg=MODAL_BG, - padx=28, - pady=22, - highlightthickness=2, - highlightbackground=ERROR_FG, + + self._modal_overlay = SolitaireModalDialog( + self.ctx, + title_txt=t("sol_forfeit_title"), + body_txt=t("sol_forfeit_desc", penalty), + is_danger=True, + buttons=[ + (t("sol_btn_cancel"), "amethyst", self._close_active_modal), + (t("sol_forfeit_confirm_new"), "fire", lambda: self._execute_forfeit(penalty, go_menu=False)), + (t("sol_forfeit_confirm_menu"), "amethyst", lambda: self._execute_forfeit(penalty, go_menu=True)), + ], ) - overlay.place(relx=0.5, rely=0.52, anchor="center") - self._modal_overlay = overlay self._sync_buttons() - tk.Label( - overlay, - text=t("sol_forfeit_title"), - font=("Georgia", 15, "bold"), - fg=ERROR_FG, - bg=MODAL_BG, - ).pack(pady=(0, 8)) - - tk.Label( - overlay, - text=t("sol_forfeit_desc", penalty), - font=("Helvetica", 10), - fg=FG_COLOR, - bg=MODAL_BG, - wraplength=430, - justify="center", - ).pack(pady=(0, 18)) - - row = tk.Frame(overlay, bg=MODAL_BG) - row.pack() - - ImageButton( - row, - t("sol_btn_cancel"), - self.ctx.assets.raw_sel, - self.ctx.assets.raw_sel_active, - self._close_active_modal, - sound_mgr=self.ctx.sounds, - width=145, - height=34, - font=("Helvetica", 9, "bold"), - ).pack(side="left", padx=5) - - ImageButton( - row, - t("sol_forfeit_confirm_new"), - self.ctx.assets.raw_btn, - self.ctx.assets.raw_btn_active, - lambda: self._execute_forfeit(penalty, go_menu=False), - sound_mgr=self.ctx.sounds, - width=175, - height=34, - font=("Helvetica", 9, "bold"), - ).pack(side="left", padx=5) - - ImageButton( - row, - t("sol_forfeit_confirm_menu"), - self.ctx.assets.raw_sel, - self.ctx.assets.raw_sel_active, - lambda: self._execute_forfeit(penalty, go_menu=True), - sound_mgr=self.ctx.sounds, - width=175, - height=34, - font=("Helvetica", 9, "bold"), - ).pack(side="left", padx=5) - def _handle_victory(self): self._game_concluded = True pid = self.ctx.profile["id"] @@ -1523,88 +1320,26 @@ class FreeCellTableView: duration_sec=dur, points_gained=xp_earned, ) - self.ctx.refresh_game_progress() + self.topbar.level_label.configure(text="") self.ctx.sounds.play("win") self._show_victory_modal(xp_earned, old_lvl, new_lvl, dur) def _show_victory_modal(self, xp_earned: int, old_lvl: int, new_lvl: int, dur: float): - overlay = tk.Frame( - self.ctx.root, - bg=MODAL_BG, - padx=30, - pady=24, - highlightthickness=2, - highlightbackground=ACCENT_GOLD, - ) - overlay.place(relx=0.5, rely=0.52, anchor="center") - self._modal_overlay = overlay - self._sync_buttons() - - frames = self.ctx.assets.get_gif_frames("win_gif") - if frames: - gif_lbl = tk.Label(overlay, bg=MODAL_BG, image=frames[0]) - gif_lbl.pack(pady=(0, 10)) - - def anim(idx: int = 0): - if not self._canvas_alive() or self._modal_overlay is None: - return - gif_lbl.configure(image=frames[idx % len(frames)]) - self._gif_job = self.ctx.root.after(90, lambda: anim(idx + 1)) - - if len(frames) > 1: - anim(0) - - tk.Label( - overlay, - text=t("sol_win_title"), - font=("Georgia", 16, "bold"), - fg=ACCENT_GOLD, - bg=MODAL_BG, - ).pack(pady=(0, 6)) - - tk.Label( - overlay, - text=t( + lines = [ + t( "sol_win_summary", self.engine.score, self.engine.moves, Database.format_seconds(dur), t(f"sol_diff_short_{self.difficulty}"), ), - font=("Helvetica", 11), - fg=FG_COLOR, - bg=MODAL_BG, - ).pack(pady=(0, 8)) - - tk.Label( - overlay, - text=t("bj_popup_xp_earned", xp_earned), - font=("Helvetica", 11, "bold"), - fg=ACCENT_GOTH, - bg=MODAL_BG, - ).pack(pady=(0, 6)) - + t("bj_popup_xp_earned", xp_earned), + ] if new_lvl > old_lvl: - tk.Label( - overlay, - text=t("bj_popup_level_up", new_lvl, Progression.get_prestige_title(new_lvl)), - font=("Georgia", 12, "bold"), - fg="#7be08a", - bg=MODAL_BG, - ).pack(pady=(2, 10)) - - btn_row = tk.Frame(overlay, bg=MODAL_BG) - btn_row.pack(pady=(12, 0)) + lines.append(t("bj_popup_level_up", new_lvl, Progression.get_prestige_title(new_lvl))) def play_again(): - if self._gif_job is not None: - try: - self.ctx.root.after_cancel(self._gif_job) - except Exception: - pass - self._gif_job = None - overlay.destroy() - self._modal_overlay = None + self._close_active_modal() self._game_concluded = False self.engine.new_game(difficulty=self.difficulty) self._check_window_focus() @@ -1618,26 +1353,14 @@ class FreeCellTableView: if callable(self.on_back_to_menu): self.on_back_to_menu() - ImageButton( - btn_row, - t("sol_play_again_btn"), - self.ctx.assets.raw_btn, - self.ctx.assets.raw_btn_active, - play_again, - sound_mgr=self.ctx.sounds, - width=175, - height=36, - font=("Helvetica", 10, "bold"), - ).pack(side="left", padx=6) - - ImageButton( - btn_row, - t("bj_popup_to_menu_btn"), - self.ctx.assets.raw_sel, - self.ctx.assets.raw_sel_active, - to_menu, - sound_mgr=self.ctx.sounds, - width=175, - height=36, - font=("Helvetica", 9 if len(t("bj_popup_to_menu_btn")) > 18 else 10, "bold"), - ).pack(side="left", padx=6) \ No newline at end of file + self._modal_overlay = SolitaireModalDialog( + self.ctx, + title_txt=t("sol_win_title"), + body_txt="\n".join(lines), + gif_key="win_gif", + buttons=[ + (t("sol_play_again_btn"), "fire", play_again), + (t("bj_popup_to_menu_btn"), "amethyst", to_menu), + ], + ) + self._sync_buttons() \ No newline at end of file diff --git a/games/solitaire/klondike/views/__pycache__/klondike_menu_view.cpython-311.pyc b/games/solitaire/klondike/views/__pycache__/klondike_menu_view.cpython-311.pyc index 26dae92..41fba50 100644 Binary files a/games/solitaire/klondike/views/__pycache__/klondike_menu_view.cpython-311.pyc and b/games/solitaire/klondike/views/__pycache__/klondike_menu_view.cpython-311.pyc differ diff --git a/games/solitaire/klondike/views/__pycache__/klondike_table_view.cpython-311.pyc b/games/solitaire/klondike/views/__pycache__/klondike_table_view.cpython-311.pyc index 421cd1e..9029cee 100644 Binary files a/games/solitaire/klondike/views/__pycache__/klondike_table_view.cpython-311.pyc and b/games/solitaire/klondike/views/__pycache__/klondike_table_view.cpython-311.pyc differ diff --git a/games/solitaire/klondike/views/klondike_menu_view.py b/games/solitaire/klondike/views/klondike_menu_view.py index 95c325d..583cbb1 100644 --- a/games/solitaire/klondike/views/klondike_menu_view.py +++ b/games/solitaire/klondike/views/klondike_menu_view.py @@ -5,7 +5,7 @@ from __future__ import annotations import json import tkinter as tk -from games.solitaire.base.solitaire_menu_chrome import create_menu_body_canvas, open_goth_modal +from games.solitaire.base.solitaire_modal_dialog import SolitaireModalDialog from games.solitaire.base.solitaire_stats_view import SolitaireStatsView from games.solitaire.klondike.views.klondike_table_view import KlondikeTableView from models.database import Database @@ -28,6 +28,7 @@ from resources.code_res.game_constants import ( from resources.code_res.i18n import t from view.widgets.goth_dropdown import GothDropdown from view.widgets.image_button import ImageButton +from view.widgets.menu_body_canvas import MenuBodyCanvas GAME_FOLDER_ID = "solitaire/klondike" GAME_TITLE_KEY = "game_title_klondike" @@ -65,7 +66,7 @@ class KlondikeMenuView: self.ctx.sounds.play_menu_music() self.ctx.root.clear_window(apply_global_bg=True) self._photo_refs.clear() - prog = self.ctx.refresh_game_progress() + self.ctx.refresh_game_progress() diff_setting_key = f"klondike_diff_{pid}" draw_setting_key = f"klondike_variant_{pid}" @@ -92,18 +93,17 @@ class KlondikeMenuView: on_back=lambda: self.show(), ).show(preselect_variant_id=pre_id) - rank_badge = f"{prog['title']} (Lv. {prog['level']} • {prog['current_xp']}/{prog['needed_xp']} XP)" self.ctx.build_game_topbar( self.ctx.root, t("kl_menu_topbar"), on_game_menu=None, on_stats=open_stats, stats_enabled=True, - extra_right_text=rank_badge, + extra_right_text="", on_lang_refresh=lambda: self.show(status_msg=status_msg, status_is_ok=status_is_ok), ) - cv = create_menu_body_canvas(self.ctx) + cv = MenuBodyCanvas(self.ctx) 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 @@ -114,9 +114,15 @@ class KlondikeMenuView: resume_btn = None if saved and saved_meta is not None: resume_btn = ImageButton( - cv, t("sol_resume_btn"), btn_fire, btn_fire, + cv, + t("sol_resume_btn"), + btn_fire, + btn_fire, lambda: self._resume_saved(saved, saved_meta["difficulty"]), - sound_mgr=self.ctx.sounds, width=190, height=38, style="fire", + sound_mgr=self.ctx.sounds, + width=180, + height=38, + style="fire", ) def switch_draw_mode(v_key: str): @@ -135,7 +141,7 @@ class KlondikeMenuView: btn_fire if is_sel else btn_purp, lambda k=v_key: switch_draw_mode(k), sound_mgr=self.ctx.sounds, - width=172, + width=162, height=36, style="fire" if is_sel else "amethyst", ) @@ -157,15 +163,21 @@ class KlondikeMenuView: ) start_btn = ImageButton( - cv, t("sol_start_btn"), btn_fire, btn_fire, + cv, + t("sol_start_btn"), + btn_fire, + btn_fire, lambda: self._on_start_clicked( selected_variant, diff_map.get(diff_var.get(), 1), saved, saved_meta ), - sound_mgr=self.ctx.sounds, width=215, height=40, style="fire", + sound_mgr=self.ctx.sounds, + width=205, + height=40, + style="fire", ) def draw_layout(w: int, h: int): - cv._sync_bg(w, h) # type: ignore[attr-defined] + cv.sync_bg(w, h) cv.delete("fg") self._photo_refs.clear() @@ -174,7 +186,9 @@ class KlondikeMenuView: x_left = cx - box_w // 2 cur_y = max(24, int(h * 0.055)) - title_ph = self.ctx.assets.get_goth_text_photo(t(GAME_TITLE_KEY), FONT_SIZE_TITLE_LG, FONT_COLOR_TITLE_MAIN, align="left") + title_ph = self.ctx.assets.get_goth_text_photo( + t(GAME_TITLE_KEY), FONT_SIZE_TITLE_LG, FONT_COLOR_TITLE_MAIN, align="left" + ) sub_ph = self.ctx.assets.get_goth_text_photo( t("sol_menu_subtitle"), FONT_SIZE_BODY, FONT_COLOR_BODY_MUTED, max_width=box_w, align="left" ) @@ -186,9 +200,11 @@ class KlondikeMenuView: if status_msg: st_ph = self.ctx.assets.get_goth_text_photo( - status_msg, FONT_SIZE_BODY, + status_msg, + FONT_SIZE_BODY, FONT_COLOR_STATUS_WIN if status_is_ok else FONT_COLOR_STATUS_LOSS, - max_width=box_w, align="left", + max_width=box_w, + align="left", ) self._photo_refs.append(st_ph) cv.create_image(x_left, cur_y, image=st_ph, anchor="nw", tags="fg") @@ -214,7 +230,10 @@ class KlondikeMenuView: saved_meta["score"], Database.format_seconds(saved_meta["elapsed_sec"]), ), - FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, max_width=box_w - 250, align="left", + FONT_SIZE_BODY, + FONT_COLOR_BODY_DEFAULT, + max_width=box_w - resume_btn.pixel_width - 70, + align="left", ) self._photo_refs.extend([rt_ph, ri_ph]) cv.create_image(x_left + 26, res_cy - 17, image=rt_ph, anchor="w", tags="fg") @@ -229,7 +248,7 @@ class KlondikeMenuView: cv.create_image(x_left + 6, cur_y, image=sec_ph, anchor="nw", tags="fg") cur_y += sec_ph.height() + 8 - setup_h = 215 + setup_h = 238 setup_cy = cur_y + setup_h // 2 s_box = self.ctx.assets.get_box_photo("box_big", (box_w, setup_h)) if s_box: @@ -237,26 +256,37 @@ class KlondikeMenuView: cv.create_image(cx, setup_cy, image=s_box, anchor="center", tags="fg") lbl_col = x_left + 32 - val_col = x_left + 225 + val_col = x_left + 220 - # Zeile 1: Zieh-Modus Toggles + Beschreibung - r1_y = cur_y + 46 - dm_lbl = self.ctx.assets.get_goth_text_photo(t("sol_draw_mode_lbl"), FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, align="left") + # Zeile 1: Zieh-Modus Toggles + Beschreibung sauber darunter (kein Anstoßen an den rechten Rahmen!) + r1_y = cur_y + 44 + dm_lbl = self.ctx.assets.get_goth_text_photo( + t("sol_draw_mode_lbl"), FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, align="left" + ) self._photo_refs.append(dm_lbl) cv.create_image(lbl_col, r1_y, image=dm_lbl, anchor="w", tags="fg") - cv.create_window(val_col, r1_y, window=draw_btns[0], anchor="w", tags="fg") - cv.create_window(val_col + 182, r1_y, window=draw_btns[1], anchor="w", tags="fg") + bx_cur = val_col + for db in draw_btns: + cv.create_window(bx_cur, r1_y, window=db, anchor="w", tags="fg") + bx_cur += db.pixel_width + 10 + + dsc_txt = t(f"kl_desc_{selected_variant}").replace("•", "-") dsc_ph = self.ctx.assets.get_goth_text_photo( - t(f"kl_desc_{selected_variant}"), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, - max_width=max(150, box_w - 225 - 375), align="left", + dsc_txt, + FONT_SIZE_SMALL_MIN, + FONT_COLOR_BODY_MUTED, + max_width=box_w - 260, + align="left", ) self._photo_refs.append(dsc_ph) - cv.create_image(val_col + 366, r1_y, image=dsc_ph, anchor="w", tags="fg") + cv.create_image(val_col, r1_y + 34, image=dsc_ph, anchor="w", tags="fg") # Zeile 2: Schwierigkeitsgrad - r2_y = cur_y + 108 - d_lbl = self.ctx.assets.get_goth_text_photo(t("sol_diff_lbl"), FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, align="left") + r2_y = cur_y + 128 + d_lbl = self.ctx.assets.get_goth_text_photo( + t("sol_diff_lbl"), FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, align="left" + ) self._photo_refs.append(d_lbl) cv.create_image(lbl_col, r2_y, image=d_lbl, anchor="w", tags="fg") @@ -323,7 +353,7 @@ class KlondikeMenuView: saved_meta["score"], Database.format_seconds(saved_meta["elapsed_sec"]), ) - self._modal_overlay = open_goth_modal( + self._modal_overlay = SolitaireModalDialog( self.ctx, title_txt=t("sol_resume_box_title"), body_txt=info_txt, @@ -383,7 +413,7 @@ class KlondikeMenuView: self._clear_modal() self._launch_fresh_game(new_variant_key, new_difficulty) - self._modal_overlay = open_goth_modal( + self._modal_overlay = SolitaireModalDialog( self.ctx, title_txt=t("sol_forfeit_title"), body_txt=t("sol_forfeit_desc", penalty), diff --git a/games/solitaire/klondike/views/klondike_table_view.py b/games/solitaire/klondike/views/klondike_table_view.py index 9abfce4..0daa544 100644 --- a/games/solitaire/klondike/views/klondike_table_view.py +++ b/games/solitaire/klondike/views/klondike_table_view.py @@ -6,8 +6,11 @@ import time import tkinter as tk from games.solitaire.base.card_animator import CardFlightAnimator +from games.solitaire.base.solitaire_bottom_bar import SolitaireBottomBar from games.solitaire.base.solitaire_core import SolitaireCard +from games.solitaire.base.solitaire_modal_dialog import SolitaireModalDialog from games.solitaire.base.solitaire_stats_view import SolitaireStatsView +from games.solitaire.base.solitaire_theme import SolitaireTableBgRenderer from games.solitaire.klondike.models.klondike_engine import KlondikeEngine from models.database import Database from models.progression import Progression @@ -18,23 +21,20 @@ from resources.code_res.game_constants import ( BORDER_COLOR, CELL_BG, ERROR_FG, - FG_COLOR, + FONT_COLOR_TITLE_MAIN, + FONT_SIZE_BODY, KLONDIKE_VARIANTS, - MODAL_BG, MUTED_FG, - PANEL_BG, PLAYING_CARD_SIZE, RED_SUITS, SOLITAIRE_DIFFICULTIES, SOLO_FORFEIT_XP_RATIO, - SUBTLE_BORDER, SUIT_SYMBOLS, SUITS, TABLE_BG, ) from resources.code_res.i18n import t from view.widgets.image_button import ImageButton -from games.solitaire.base.solitaire_theme import SolitaireTableBgRenderer GAME_FOLDER_ID = "solitaire/klondike" GAME_TITLE_KEY = "game_title_klondike" @@ -90,12 +90,12 @@ class KlondikeTableView: self._hint_job: str | None = None self._auto_job: str | None = None self._resize_job: str | None = None - self._gif_job: str | None = None self._bind_ids: list[tuple[str, str]] = [] self._auto_running = False self.animator: CardFlightAnimator | None = None self._bg_renderer = SolitaireTableBgRenderer(self.ctx.assets.res) self._frame_bot_pad: int = 18 + self._canvas_ui_refs: list = [] self._card_aspect: float | None = None self.card_size: tuple[int, int] = PLAYING_CARD_SIZE @@ -111,7 +111,7 @@ class KlondikeTableView: self._last_click_ts: float = 0.0 self._last_click_target: tuple | None = None self._active_hint: dict | None = None - self._modal_overlay: tk.Frame | None = None + self._modal_overlay: tk.Widget | None = None self._build_ui() if not resume_state_json: @@ -125,9 +125,6 @@ class KlondikeTableView: d_mult = SOLITAIRE_DIFFICULTIES.get(self.difficulty, SOLITAIRE_DIFFICULTIES[1])["xp_mult"] return self.cfg["xp_mult"] * d_mult - # ========================================================================= - # UI-Aufbau, Fokus-Überwachung, Exit-Save & Lifecycle - # ========================================================================= def _canvas_alive(self) -> bool: if not self._alive: return False @@ -177,14 +174,13 @@ class KlondikeTableView: self._hint_job, self._auto_job, self._resize_job, - self._gif_job, ): if job is not None: try: self.ctx.root.after_cancel(job) except Exception: pass - self._tick_job = self._focus_job = self._hint_job = self._auto_job = self._resize_job = self._gif_job = None + self._tick_job = self._focus_job = self._hint_job = self._auto_job = self._resize_job = None for seq, func_id in self._bind_ids: try: @@ -221,7 +217,6 @@ class KlondikeTableView: self._window_active = has_focus if should_run: - # Startet den Timer nur dann weiter, wenn das Spiel bereits aktiv begonnen wurde self.engine.resume_timer() else: if not prev_paused: @@ -235,13 +230,12 @@ class KlondikeTableView: def _build_ui(self): self._play_table_music() - self.ctx.root.clear_window(apply_global_bg=False) - self.ctx.root.configure(bg=BG_COLOR) + self.ctx.root.clear_window(apply_global_bg=True) self.ctx.refresh_game_progress() self.topbar = self.ctx.build_game_topbar( self.ctx.root, - f"{t(f'variant_{self.variant_key}')} • {t(f'sol_diff_short_{self.difficulty}')}", + t(GAME_TITLE_KEY), on_game_menu=self._back_to_game_menu, on_stats=self._open_stats, stats_enabled=True, @@ -249,113 +243,49 @@ class KlondikeTableView: on_lang_refresh=self._refresh_lang, ) - ctrl_bar = tk.Frame( - self.ctx.root, - bg=PANEL_BG, - padx=14, - pady=8, - highlightthickness=1, - highlightbackground=BORDER_COLOR, - ) - ctrl_bar.pack(fill="x", padx=14, pady=(6, 4)) - self.hud_var = tk.StringVar(value="") - tk.Label( - ctrl_bar, - textvariable=self.hud_var, - font=("Georgia", 11, "bold"), - fg=ACCENT_GOLD, - bg=PANEL_BG, - ).pack(side="left") - self.status_var = tk.StringVar(value="") - tk.Label( - ctrl_bar, - textvariable=self.status_var, - font=("Helvetica", 9, "bold"), - fg=ACCENT_GOTH, - bg=PANEL_BG, - ).pack(side="left", padx=(14, 0)) - btn_box = tk.Frame(ctrl_bar, bg=PANEL_BG) - btn_box.pack(side="right") + # Untere Gothic-Leiste mit box_gold_double Rahmen unter dem Spielfeld + self.bottom_bar = SolitaireBottomBar(self.ctx.root, self.ctx, self.hud_var, self.status_var) + self.bottom_bar.pack(fill="x", side="bottom", padx=14, pady=(4, 10)) + + 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.undo_btn = ImageButton( - btn_box, - t("sol_btn_undo"), - self.ctx.assets.raw_sel, - self.ctx.assets.raw_sel_active, - self._on_undo, - sound_mgr=self.ctx.sounds, - width=152, - height=32, - font=("Helvetica", 9, "bold"), - enabled=self.engine.can_undo, + self.bottom_bar, t("sol_btn_undo"), btn_norm, btn_purp, + self._on_undo, sound_mgr=self.ctx.sounds, width=136, height=32, + enabled=self.engine.can_undo, style="amethyst", ) - self.undo_btn.pack(side="left", padx=3) - self.undo_all_btn = ImageButton( - btn_box, - t("sol_btn_undo_all"), - self.ctx.assets.raw_sel, - self.ctx.assets.raw_sel_active, - self._on_undo_all, - sound_mgr=self.ctx.sounds, - width=105, - height=32, - font=("Helvetica", 9, "bold"), - enabled=self.engine.can_undo_all, + self.bottom_bar, t("sol_btn_undo_all"), btn_norm, btn_purp, + self._on_undo_all, sound_mgr=self.ctx.sounds, width=92, height=32, + enabled=self.engine.can_undo_all, style="amethyst", ) - self.undo_all_btn.pack(side="left", padx=3) - self.hint_btn = ImageButton( - btn_box, - t("sol_btn_hint"), - self.ctx.assets.raw_sel, - self.ctx.assets.raw_sel_active, - self._on_hint, - sound_mgr=self.ctx.sounds, - width=102, - height=32, - font=("Helvetica", 9, "bold"), - enabled=not self.engine.won, + self.bottom_bar, t("sol_btn_hint"), btn_norm, btn_purp, + self._on_hint, sound_mgr=self.ctx.sounds, width=92, height=32, + enabled=not self.engine.won, style="amethyst", ) - self.hint_btn.pack(side="left", padx=3) - self.auto_btn = ImageButton( - btn_box, - t("sol_btn_autocomplete"), - self.ctx.assets.raw_btn, - self.ctx.assets.raw_btn_active, - self._start_auto_complete, - sound_mgr=self.ctx.sounds, - width=122, - height=32, - font=("Helvetica", 9, "bold"), - enabled=self.engine.can_auto_complete(), + self.bottom_bar, t("sol_btn_autocomplete"), btn_fire, btn_fire, + self._start_auto_complete, sound_mgr=self.ctx.sounds, width=112, height=32, + enabled=self.engine.can_auto_complete(), style="fire", ) - self.auto_btn.pack(side="left", padx=3) - self.new_btn = ImageButton( - btn_box, + self.bottom_bar, t("sol_btn_forfeit") if self.engine.moves > 0 else t("sol_btn_new_deal"), - self.ctx.assets.raw_sel, - self.ctx.assets.raw_sel_active, - self._on_new_or_forfeit_clicked, - sound_mgr=self.ctx.sounds, - width=112, - height=32, - font=("Helvetica", 9, "bold"), + btn_norm, btn_purp, self._on_new_or_forfeit_clicked, + sound_mgr=self.ctx.sounds, width=104, height=32, style="amethyst", ) - self.new_btn.pack(side="left", padx=(3, 0)) + self.bottom_bar.set_buttons([ + self.undo_btn, self.undo_all_btn, self.hint_btn, self.auto_btn, self.new_btn + ]) - self.canvas = tk.Canvas( - self.ctx.root, - bg=TABLE_BG, - highlightthickness=1, - highlightbackground=SUBTLE_BORDER, - ) - self.canvas.pack(fill="both", expand=True, padx=14, pady=(2, 12)) + self.canvas = tk.Canvas(self.ctx.root, bg=TABLE_BG, bd=0, highlightthickness=0) + self.canvas.pack(fill="both", expand=True, padx=14, pady=(4, 2)) self.animator = CardFlightAnimator(self.ctx.root, self.canvas) self.canvas.bind("", self._on_canvas_configure) @@ -458,9 +388,6 @@ class KlondikeTableView: return Database.save_game_state(pid, GAME_FOLDER_ID, self.variant_key, self.engine.to_json()) - # ========================================================================= - # Uhr, stiller Zeit-Checkpoint & HUD - # ========================================================================= def _start_clock(self): if not self._canvas_alive(): return @@ -485,7 +412,10 @@ class KlondikeTableView: elapsed_str = Database.format_seconds(self.engine.get_elapsed_seconds()) paused_tag = t("sol_hud_paused_tag") if (self.engine.is_timer_paused and not self.engine.won) else "" diff_label = t(f"sol_diff_short_{self.difficulty}") - self.hud_var.set(t("sol_hud_stats", self.engine.score, self.engine.moves, elapsed_str, paused_tag, diff_label)) + new_hud = t("sol_hud_stats", self.engine.score, self.engine.moves, elapsed_str, paused_tag, diff_label) + # Nur schreiben, wenn sich der Text tatsächlich geändert hat! + if self.hud_var.get() != new_hud: + self.hud_var.set(new_hud) except Exception: pass @@ -499,18 +429,12 @@ class KlondikeTableView: self.auto_btn.set_enabled((not locked) and self.engine.can_auto_complete()) self.new_btn.set_enabled(not self._auto_running) new_lbl = t("sol_btn_forfeit") if (self.engine.moves > 0 and not self.engine.won) else t("sol_btn_new_deal") - if hasattr(self.new_btn, "set_text"): - self.new_btn.set_text(new_lbl) - elif hasattr(self.new_btn, "configure"): - try: - self.new_btn.configure(text=new_lbl) - except Exception: - pass + prev_w = self.new_btn.pixel_width + self.new_btn.set_text(new_lbl) + if self.new_btn.pixel_width != prev_w: + self.bottom_bar.relayout() self._update_hud_text() - # ========================================================================= - # Kartenpositions-Berechnung & Animations-Helfer - # ========================================================================= @staticmethod def _card_key(card: SolitaireCard) -> tuple[str, str, int]: return (card.suit, card.rank, card.deck_id) @@ -522,7 +446,6 @@ class KlondikeTableView: canvas_h = max(420, self.canvas.winfo_height()) avail_h = max(180, canvas_h - self._tableau_y - self._frame_bot_pad) - down_cnt = sum(1 for c in cards if not c.face_up) up_cnt = max(0, len(cards) - down_cnt - 1) down_dy = max(7, int(ch * 0.095)) @@ -647,9 +570,6 @@ class KlondikeTableView: self.animator.start(flights, self._draw_card_at, duration_ms=duration_ms, on_done=finish) return True - # ========================================================================= - # Ausgewogenes Layout & Rendering - # ========================================================================= def _on_canvas_configure(self, _event=None): if not self._canvas_alive(): return @@ -787,7 +707,11 @@ class KlondikeTableView: ): if not self._canvas_alive(): return - self.canvas.delete("all") + bg_ids = set(self.canvas.find_withtag("table_bg_slice")) + for item_id in self.canvas.find_all(): + if item_id not in bg_ids: + self.canvas.delete(item_id) + self._canvas_ui_refs.clear() cw, ch = self.card_size canvas_w = max(640, self.canvas.winfo_width()) canvas_h = max(420, self.canvas.winfo_height()) @@ -925,35 +849,26 @@ class KlondikeTableView: next_y = ys[c_idx + 1] if not is_last else (cur_y + ch) self._tableau_card_rects[col_idx].append((tx, cur_y, tx + cw, next_y)) - # Pause-Banner nur anzeigen, wenn der Timer bereits aktiv gestartet wurde + # Pause-Banner mit box_purple + Old London if ( self.engine.has_timer_started and not self._window_active and not self.engine.won and self._modal_overlay is None ): - bw, bh = 430, 42 - bx = (canvas_w - bw) // 2 - by = canvas_h - bh - 12 - self.canvas.create_rectangle( - bx, by, bx + bw, by + bh, - fill=MODAL_BG, - outline=ACCENT_GOTH, - width=2, - ) - self.canvas.create_text( - bx + bw // 2, - by + bh // 2, - text=t("sol_canvas_paused_banner"), - font=("Helvetica", 10, "bold"), - fill=ACCENT_GOLD, + p_ph = self.ctx.assets.get_goth_text_photo( + t("sol_canvas_paused_banner"), FONT_SIZE_BODY, FONT_COLOR_TITLE_MAIN ) + bw, bh = p_ph.width() + 56, max(44, p_ph.height() + 18) + box_ph = self.ctx.assets.get_box_photo("box_purple", (bw, bh)) + self._canvas_ui_refs.extend([p_ph, box_ph] if box_ph else [p_ph]) + pcx, pcy = canvas_w // 2, canvas_h - bh // 2 - 18 + if box_ph: + self.canvas.create_image(pcx, pcy, image=box_ph, anchor="center") + self.canvas.create_image(pcx, pcy, image=p_ph, anchor="center") self._sync_buttons() - # ========================================================================= - # Hit-Testing & Maus-Steuerung (Timer startet erst bei echtem Treffer!) - # ========================================================================= def _hit_test(self, x: int, y: int) -> dict | None: cw, ch = self.card_size @@ -1015,7 +930,6 @@ class KlondikeTableView: self._dragging = False if not hit: return - # Erste echte Interaktion mit einer Karte / dem Stock -> jetzt startet die Spielzeit! self.engine.start_timer_if_needed() self._update_hud_text() hit["start_xy"] = (event.x, event.y) @@ -1215,13 +1129,10 @@ class KlondikeTableView: if zone == "tableau": return self.engine.move_tableau_to_tableau(info["col"], info["idx"], best_col) if zone == "foundation": - return self.engine.move_foundation_to_tableau(info["col"], best_col) + return self.engine.move_foundation_to_tableau(info["col"], dst_col=best_col) return False - # ========================================================================= - # Aktionen: Undo, Undo All, Deadlock-Check, Auto-Complete, Aufgeben & Sieg - # ========================================================================= def _after_player_move(self): if self.engine.is_stagnation_locked(): self.status_var.set(t("sol_stock_stagnant_msg")) @@ -1384,7 +1295,7 @@ class KlondikeTableView: ) updated = Database.adjust_game_points(pid, GAME_FOLDER_ID, -penalty, min_floor_xp=floor_xp) deducted = max(0, prog["total_points"] - updated["total_points"]) - self.ctx.refresh_game_progress() + self.topbar.level_label.configure(text="") self.ctx.sounds.play("lose") if self._modal_overlay is not None: @@ -1409,39 +1320,6 @@ class KlondikeTableView: self._save_progress() penalty = self._compute_forfeit_penalty() - overlay = tk.Frame( - self.ctx.root, - bg=MODAL_BG, - padx=28, - pady=22, - highlightthickness=2, - highlightbackground=ACCENT_GOTH, - ) - overlay.place(relx=0.5, rely=0.52, anchor="center") - self._modal_overlay = overlay - self._sync_buttons() - - tk.Label( - overlay, - text=t("sol_deadlock_title"), - font=("Georgia", 15, "bold"), - fg=ERROR_FG, - bg=MODAL_BG, - ).pack(pady=(0, 8)) - - tk.Label( - overlay, - text=t("sol_deadlock_desc", penalty), - font=("Helvetica", 10), - fg=FG_COLOR, - bg=MODAL_BG, - wraplength=460, - justify="center", - ).pack(pady=(0, 18)) - - row = tk.Frame(overlay, bg=MODAL_BG) - row.pack() - def undo_step(): self._close_active_modal() self._on_undo() @@ -1450,117 +1328,37 @@ class KlondikeTableView: self._close_active_modal() self._on_undo_all() - ImageButton( - row, - t("sol_deadlock_btn_undo"), - self.ctx.assets.raw_btn, - self.ctx.assets.raw_btn_active, - undo_step, - sound_mgr=self.ctx.sounds, - width=170, - height=36, - font=("Helvetica", 9, "bold"), - enabled=self.engine.can_undo, - ).pack(side="left", padx=5) - - ImageButton( - row, - t("sol_deadlock_btn_undo_all"), - self.ctx.assets.raw_btn, - self.ctx.assets.raw_btn_active, - undo_everything, - sound_mgr=self.ctx.sounds, - width=175, - height=36, - font=("Helvetica", 9, "bold"), - enabled=self.engine.can_undo_all, - ).pack(side="left", padx=5) - - ImageButton( - row, - t("sol_deadlock_btn_end", penalty), - self.ctx.assets.raw_sel, - self.ctx.assets.raw_sel_active, - lambda: self._execute_forfeit(penalty, go_menu=True), - sound_mgr=self.ctx.sounds, - width=165, - height=36, - font=("Helvetica", 9, "bold"), - ).pack(side="left", padx=5) + self._modal_overlay = SolitaireModalDialog( + self.ctx, + title_txt=t("sol_deadlock_title"), + body_txt=t("sol_deadlock_desc", penalty), + is_danger=True, + buttons=[ + (t("sol_deadlock_btn_undo"), "fire", undo_step, self.engine.can_undo), + (t("sol_deadlock_btn_undo_all"), "fire", undo_everything, self.engine.can_undo_all), + (t("sol_deadlock_btn_end", penalty), "amethyst", lambda: self._execute_forfeit(penalty, go_menu=True), True), + ], + ) + self._sync_buttons() def _show_forfeit_modal(self): self.engine.pause_timer() self._save_progress() penalty = self._compute_forfeit_penalty() - overlay = tk.Frame( - self.ctx.root, - bg=MODAL_BG, - padx=28, - pady=22, - highlightthickness=2, - highlightbackground=ERROR_FG, + + self._modal_overlay = SolitaireModalDialog( + self.ctx, + title_txt=t("sol_forfeit_title"), + body_txt=t("sol_forfeit_desc", penalty), + is_danger=True, + buttons=[ + (t("sol_btn_cancel"), "amethyst", self._close_active_modal), + (t("sol_forfeit_confirm_new"), "fire", lambda: self._execute_forfeit(penalty, go_menu=False)), + (t("sol_forfeit_confirm_menu"), "amethyst", lambda: self._execute_forfeit(penalty, go_menu=True)), + ], ) - overlay.place(relx=0.5, rely=0.52, anchor="center") - self._modal_overlay = overlay self._sync_buttons() - tk.Label( - overlay, - text=t("sol_forfeit_title"), - font=("Georgia", 15, "bold"), - fg=ERROR_FG, - bg=MODAL_BG, - ).pack(pady=(0, 8)) - - tk.Label( - overlay, - text=t("sol_forfeit_desc", penalty), - font=("Helvetica", 10), - fg=FG_COLOR, - bg=MODAL_BG, - wraplength=430, - justify="center", - ).pack(pady=(0, 18)) - - row = tk.Frame(overlay, bg=MODAL_BG) - row.pack() - - ImageButton( - row, - t("sol_btn_cancel"), - self.ctx.assets.raw_sel, - self.ctx.assets.raw_sel_active, - self._close_active_modal, - sound_mgr=self.ctx.sounds, - width=145, - height=34, - font=("Helvetica", 9, "bold"), - ).pack(side="left", padx=5) - - ImageButton( - row, - t("sol_forfeit_confirm_new"), - self.ctx.assets.raw_btn, - self.ctx.assets.raw_btn_active, - lambda: self._execute_forfeit(penalty, go_menu=False), - sound_mgr=self.ctx.sounds, - width=175, - height=34, - font=("Helvetica", 9, "bold"), - ).pack(side="left", padx=5) - - ImageButton( - row, - t("sol_forfeit_confirm_menu"), - self.ctx.assets.raw_sel, - self.ctx.assets.raw_sel_active, - lambda: self._execute_forfeit(penalty, go_menu=True), - sound_mgr=self.ctx.sounds, - width=175, - height=34, - font=("Helvetica", 9, "bold"), - ).pack(side="left", padx=5) - def _handle_victory(self): self._game_concluded = True pid = self.ctx.profile["id"] @@ -1583,88 +1381,26 @@ class KlondikeTableView: duration_sec=dur, points_gained=xp_earned, ) - self.ctx.refresh_game_progress() + self.topbar.level_label.configure(text="") self.ctx.sounds.play("win") self._show_victory_modal(xp_earned, old_lvl, new_lvl, dur) def _show_victory_modal(self, xp_earned: int, old_lvl: int, new_lvl: int, dur: float): - overlay = tk.Frame( - self.ctx.root, - bg=MODAL_BG, - padx=30, - pady=24, - highlightthickness=2, - highlightbackground=ACCENT_GOLD, - ) - overlay.place(relx=0.5, rely=0.52, anchor="center") - self._modal_overlay = overlay - self._sync_buttons() - - frames = self.ctx.assets.get_gif_frames("win_gif") - if frames: - gif_lbl = tk.Label(overlay, bg=MODAL_BG, image=frames[0]) - gif_lbl.pack(pady=(0, 10)) - - def anim(idx: int = 0): - if not self._canvas_alive() or self._modal_overlay is None: - return - gif_lbl.configure(image=frames[idx % len(frames)]) - self._gif_job = self.ctx.root.after(90, lambda: anim(idx + 1)) - - if len(frames) > 1: - anim(0) - - tk.Label( - overlay, - text=t("sol_win_title"), - font=("Georgia", 16, "bold"), - fg=ACCENT_GOLD, - bg=MODAL_BG, - ).pack(pady=(0, 6)) - - tk.Label( - overlay, - text=t( + lines = [ + t( "sol_win_summary", self.engine.score, self.engine.moves, Database.format_seconds(dur), t(f"sol_diff_short_{self.difficulty}"), ), - font=("Helvetica", 11), - fg=FG_COLOR, - bg=MODAL_BG, - ).pack(pady=(0, 8)) - - tk.Label( - overlay, - text=t("bj_popup_xp_earned", xp_earned), - font=("Helvetica", 11, "bold"), - fg=ACCENT_GOTH, - bg=MODAL_BG, - ).pack(pady=(0, 6)) - + t("bj_popup_xp_earned", xp_earned), + ] if new_lvl > old_lvl: - tk.Label( - overlay, - text=t("bj_popup_level_up", new_lvl, Progression.get_prestige_title(new_lvl)), - font=("Georgia", 12, "bold"), - fg="#7be08a", - bg=MODAL_BG, - ).pack(pady=(2, 10)) - - btn_row = tk.Frame(overlay, bg=MODAL_BG) - btn_row.pack(pady=(12, 0)) + lines.append(t("bj_popup_level_up", new_lvl, Progression.get_prestige_title(new_lvl))) def play_again(): - if self._gif_job is not None: - try: - self.ctx.root.after_cancel(self._gif_job) - except Exception: - pass - self._gif_job = None - overlay.destroy() - self._modal_overlay = None + self._close_active_modal() self._game_concluded = False self.engine.new_game(draw_count=self.cfg["draw_count"], difficulty=self.difficulty) self._check_window_focus() @@ -1678,26 +1414,14 @@ class KlondikeTableView: if callable(self.on_back_to_menu): self.on_back_to_menu() - ImageButton( - btn_row, - t("sol_play_again_btn"), - self.ctx.assets.raw_btn, - self.ctx.assets.raw_btn_active, - play_again, - sound_mgr=self.ctx.sounds, - width=175, - height=36, - font=("Helvetica", 10, "bold"), - ).pack(side="left", padx=6) - - ImageButton( - btn_row, - t("bj_popup_to_menu_btn"), - self.ctx.assets.raw_sel, - self.ctx.assets.raw_sel_active, - to_menu, - sound_mgr=self.ctx.sounds, - width=175, - height=36, - font=("Helvetica", 9 if len(t("bj_popup_to_menu_btn")) > 18 else 10, "bold"), - ).pack(side="left", padx=6) \ No newline at end of file + self._modal_overlay = SolitaireModalDialog( + self.ctx, + title_txt=t("sol_win_title"), + body_txt="\n".join(lines), + gif_key="win_gif", + buttons=[ + (t("sol_play_again_btn"), "fire", play_again), + (t("bj_popup_to_menu_btn"), "amethyst", to_menu), + ], + ) + self._sync_buttons() \ No newline at end of file diff --git a/games/solitaire/spider_solitaire/views/__pycache__/spider_menu_view.cpython-311.pyc b/games/solitaire/spider_solitaire/views/__pycache__/spider_menu_view.cpython-311.pyc index d60c097..b9ea169 100644 Binary files a/games/solitaire/spider_solitaire/views/__pycache__/spider_menu_view.cpython-311.pyc and b/games/solitaire/spider_solitaire/views/__pycache__/spider_menu_view.cpython-311.pyc differ diff --git a/games/solitaire/spider_solitaire/views/__pycache__/spider_table_view.cpython-311.pyc b/games/solitaire/spider_solitaire/views/__pycache__/spider_table_view.cpython-311.pyc index 93a3370..c11356a 100644 Binary files a/games/solitaire/spider_solitaire/views/__pycache__/spider_table_view.cpython-311.pyc and b/games/solitaire/spider_solitaire/views/__pycache__/spider_table_view.cpython-311.pyc differ diff --git a/games/solitaire/spider_solitaire/views/spider_menu_view.py b/games/solitaire/spider_solitaire/views/spider_menu_view.py index e8939c8..9e78723 100644 --- a/games/solitaire/spider_solitaire/views/spider_menu_view.py +++ b/games/solitaire/spider_solitaire/views/spider_menu_view.py @@ -5,7 +5,7 @@ from __future__ import annotations import json import tkinter as tk -from games.solitaire.base.solitaire_menu_chrome import create_menu_body_canvas, open_goth_modal +from games.solitaire.base.solitaire_modal_dialog import SolitaireModalDialog from games.solitaire.base.solitaire_stats_view import SolitaireStatsView from games.solitaire.spider_solitaire.views.spider_table_view import SpiderTableView from models.database import Database @@ -28,6 +28,7 @@ from resources.code_res.game_constants import ( from resources.code_res.i18n import t from view.widgets.goth_dropdown import GothDropdown from view.widgets.image_button import ImageButton +from view.widgets.menu_body_canvas import MenuBodyCanvas GAME_FOLDER_ID = "solitaire/spider_solitaire" GAME_TITLE_KEY = "game_title_spider_solitaire" @@ -65,7 +66,7 @@ class SpiderMenuView: self.ctx.sounds.play_menu_music() self.ctx.root.clear_window(apply_global_bg=True) self._photo_refs.clear() - prog = self.ctx.refresh_game_progress() + self.ctx.refresh_game_progress() diff_setting_key = f"spider_diff_{pid}" var_setting_key = f"spider_variant_{pid}" @@ -92,18 +93,17 @@ class SpiderMenuView: on_back=lambda: self.show(), ).show(preselect_variant_id=pre_id) - rank_badge = f"{prog['title']} (Lv. {prog['level']} • {prog['current_xp']}/{prog['needed_xp']} XP)" self.ctx.build_game_topbar( self.ctx.root, t("sp_menu_topbar"), on_game_menu=None, on_stats=open_stats, stats_enabled=True, - extra_right_text=rank_badge, + extra_right_text="", on_lang_refresh=lambda: self.show(status_msg=status_msg, status_is_ok=status_is_ok), ) - cv = create_menu_body_canvas(self.ctx) + cv = MenuBodyCanvas(self.ctx) 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 @@ -114,9 +114,15 @@ class SpiderMenuView: resume_btn = None if saved and saved_meta is not None: resume_btn = ImageButton( - cv, t("sol_resume_btn"), btn_fire, btn_fire, + cv, + t("sol_resume_btn"), + btn_fire, + btn_fire, lambda: self._resume_saved(saved, saved_meta["difficulty"]), - sound_mgr=self.ctx.sounds, width=190, height=38, style="fire", + sound_mgr=self.ctx.sounds, + width=180, + height=38, + style="fire", ) def switch_suit_mode(v_key: str): @@ -140,7 +146,7 @@ class SpiderMenuView: btn_fire if is_sel else btn_purp, lambda k=v_key: switch_suit_mode(k), sound_mgr=self.ctx.sounds, - width=168, + width=158, height=36, style="fire" if is_sel else "amethyst", ) @@ -162,15 +168,21 @@ class SpiderMenuView: ) start_btn = ImageButton( - cv, t("sol_start_btn"), btn_fire, btn_fire, + cv, + t("sol_start_btn"), + btn_fire, + btn_fire, lambda: self._on_start_clicked( selected_variant, diff_map.get(diff_var.get(), 1), saved, saved_meta ), - sound_mgr=self.ctx.sounds, width=215, height=40, style="fire", + sound_mgr=self.ctx.sounds, + width=205, + height=40, + style="fire", ) def draw_layout(w: int, h: int): - cv._sync_bg(w, h) # type: ignore[attr-defined] + cv.sync_bg(w, h) cv.delete("fg") self._photo_refs.clear() @@ -179,7 +191,9 @@ class SpiderMenuView: x_left = cx - box_w // 2 cur_y = max(22, int(h * 0.05)) - title_ph = self.ctx.assets.get_goth_text_photo(t(GAME_TITLE_KEY), FONT_SIZE_TITLE_LG, FONT_COLOR_TITLE_MAIN, align="left") + title_ph = self.ctx.assets.get_goth_text_photo( + t(GAME_TITLE_KEY), FONT_SIZE_TITLE_LG, FONT_COLOR_TITLE_MAIN, align="left" + ) sub_ph = self.ctx.assets.get_goth_text_photo( t("sp_menu_subtitle"), FONT_SIZE_BODY, FONT_COLOR_BODY_MUTED, max_width=box_w, align="left" ) @@ -191,9 +205,11 @@ class SpiderMenuView: if status_msg: st_ph = self.ctx.assets.get_goth_text_photo( - status_msg, FONT_SIZE_BODY, + status_msg, + FONT_SIZE_BODY, FONT_COLOR_STATUS_WIN if status_is_ok else FONT_COLOR_STATUS_LOSS, - max_width=box_w, align="left", + max_width=box_w, + align="left", ) self._photo_refs.append(st_ph) cv.create_image(x_left, cur_y, image=st_ph, anchor="nw", tags="fg") @@ -219,7 +235,10 @@ class SpiderMenuView: saved_meta["score"], Database.format_seconds(saved_meta["elapsed_sec"]), ), - FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, max_width=box_w - 250, align="left", + FONT_SIZE_BODY, + FONT_COLOR_BODY_DEFAULT, + max_width=box_w - resume_btn.pixel_width - 70, + align="left", ) self._photo_refs.extend([rt_ph, ri_ph]) cv.create_image(x_left + 26, res_cy - 17, image=rt_ph, anchor="w", tags="fg") @@ -242,26 +261,33 @@ class SpiderMenuView: cv.create_image(cx, setup_cy, image=s_box, anchor="center", tags="fg") lbl_col = x_left + 32 - val_col = x_left + 225 + val_col = x_left + 220 # Zeile 1: 1 / 2 / 4 Farben Toggles + Kurzbeschreibung darunter r1_y = cur_y + 44 - sm_lbl = self.ctx.assets.get_goth_text_photo(t("sp_suit_mode_lbl"), FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, align="left") + sm_lbl = self.ctx.assets.get_goth_text_photo( + t("sp_suit_mode_lbl"), FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, align="left" + ) self._photo_refs.append(sm_lbl) cv.create_image(lbl_col, r1_y, image=sm_lbl, anchor="w", tags="fg") - for idx, sb in enumerate(suit_btns): - cv.create_window(val_col + idx * 178, r1_y, window=sb, anchor="w", tags="fg") + bx_cur = val_col + for sb in suit_btns: + cv.create_window(bx_cur, r1_y, window=sb, anchor="w", tags="fg") + bx_cur += sb.pixel_width + 10 + + dsc_txt = t(f"sp_desc_{selected_variant}").replace("•", "-") dsc_ph = self.ctx.assets.get_goth_text_photo( - t(f"sp_desc_{selected_variant}"), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, - max_width=box_w - 260, align="left", + dsc_txt, FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, max_width=box_w - 260, align="left" ) self._photo_refs.append(dsc_ph) cv.create_image(val_col, r1_y + 34, image=dsc_ph, anchor="w", tags="fg") # Zeile 2: Schwierigkeitsgrad r2_y = cur_y + 128 - d_lbl = self.ctx.assets.get_goth_text_photo(t("sol_diff_lbl"), FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, align="left") + d_lbl = self.ctx.assets.get_goth_text_photo( + t("sol_diff_lbl"), FONT_SIZE_BODY, FONT_COLOR_BODY_DEFAULT, align="left" + ) self._photo_refs.append(d_lbl) cv.create_image(lbl_col, r2_y, image=d_lbl, anchor="w", tags="fg") @@ -328,7 +354,7 @@ class SpiderMenuView: saved_meta["score"], Database.format_seconds(saved_meta["elapsed_sec"]), ) - self._modal_overlay = open_goth_modal( + self._modal_overlay = SolitaireModalDialog( self.ctx, title_txt=t("sol_resume_box_title"), body_txt=info_txt, @@ -388,7 +414,7 @@ class SpiderMenuView: self._clear_modal() self._launch_fresh_game(new_variant_key, new_difficulty) - self._modal_overlay = open_goth_modal( + self._modal_overlay = SolitaireModalDialog( self.ctx, title_txt=t("sol_forfeit_title"), body_txt=t("sol_forfeit_desc", penalty), diff --git a/games/solitaire/spider_solitaire/views/spider_table_view.py b/games/solitaire/spider_solitaire/views/spider_table_view.py index ea2aad7..eb689bb 100644 --- a/games/solitaire/spider_solitaire/views/spider_table_view.py +++ b/games/solitaire/spider_solitaire/views/spider_table_view.py @@ -6,8 +6,11 @@ import time import tkinter as tk from games.solitaire.base.card_animator import CardFlightAnimator +from games.solitaire.base.solitaire_bottom_bar import SolitaireBottomBar from games.solitaire.base.solitaire_core import SolitaireCard +from games.solitaire.base.solitaire_modal_dialog import SolitaireModalDialog from games.solitaire.base.solitaire_stats_view import SolitaireStatsView +from games.solitaire.base.solitaire_theme import SolitaireTableBgRenderer from games.solitaire.spider_solitaire.models.spider_engine import SpiderEngine from models.database import Database from models.progression import Progression @@ -18,10 +21,9 @@ from resources.code_res.game_constants import ( BORDER_COLOR, CELL_BG, ERROR_FG, - FG_COLOR, - MODAL_BG, + FONT_COLOR_TITLE_MAIN, + FONT_SIZE_BODY, MUTED_FG, - PANEL_BG, PLAYING_CARD_SIZE, SOLITAIRE_DIFFICULTIES, SOLO_FORFEIT_XP_RATIO, @@ -31,7 +33,6 @@ from resources.code_res.game_constants import ( ) from resources.code_res.i18n import t from view.widgets.image_button import ImageButton -from games.solitaire.base.solitaire_theme import SolitaireTableBgRenderer GAME_FOLDER_ID = "solitaire/spider_solitaire" GAME_TITLE_KEY = "game_title_spider_solitaire" @@ -83,11 +84,11 @@ class SpiderTableView: self._focus_job: str | None = None self._hint_job: str | None = None self._resize_job: str | None = None - self._gif_job: str | None = None self._bind_ids: list[tuple[str, str]] = [] self.animator: CardFlightAnimator | None = None self._bg_renderer = SolitaireTableBgRenderer(self.ctx.assets.res) self._frame_bot_pad: int = 18 + self._canvas_ui_refs: list = [] self._card_aspect: float | None = None self.card_size: tuple[int, int] = PLAYING_CARD_SIZE @@ -103,7 +104,7 @@ class SpiderTableView: self._last_click_ts: float = 0.0 self._last_click_target: tuple | None = None self._active_hint: dict | None = None - self._modal_overlay: tk.Frame | None = None + self._modal_overlay: tk.Widget | None = None self._build_ui() if not resume_state_json: @@ -117,9 +118,6 @@ class SpiderTableView: d_mult = SOLITAIRE_DIFFICULTIES.get(self.difficulty, SOLITAIRE_DIFFICULTIES[1])["xp_mult"] return self.cfg["xp_mult"] * d_mult - # ========================================================================= - # UI-Aufbau, Fokus-Überwachung, Exit-Save & Lifecycle - # ========================================================================= def _canvas_alive(self) -> bool: if not self._alive: return False @@ -168,14 +166,13 @@ class SpiderTableView: self._focus_job, self._hint_job, self._resize_job, - self._gif_job, ): if job is not None: try: self.ctx.root.after_cancel(job) except Exception: pass - self._tick_job = self._focus_job = self._hint_job = self._resize_job = self._gif_job = None + self._tick_job = self._focus_job = self._hint_job = self._resize_job = None for seq, func_id in self._bind_ids: try: @@ -225,13 +222,12 @@ class SpiderTableView: def _build_ui(self): self._play_table_music() - self.ctx.root.clear_window(apply_global_bg=False) - self.ctx.root.configure(bg=BG_COLOR) + self.ctx.root.clear_window(apply_global_bg=True) self.ctx.refresh_game_progress() self.topbar = self.ctx.build_game_topbar( self.ctx.root, - f"{t(f'variant_{self.variant_key}')} • {t(f'sol_diff_short_{self.difficulty}')}", + t(GAME_TITLE_KEY), on_game_menu=self._back_to_game_menu, on_stats=self._open_stats, stats_enabled=True, @@ -239,99 +235,43 @@ class SpiderTableView: on_lang_refresh=self._refresh_lang, ) - ctrl_bar = tk.Frame( - self.ctx.root, - bg=PANEL_BG, - padx=14, - pady=8, - highlightthickness=1, - highlightbackground=BORDER_COLOR, - ) - ctrl_bar.pack(fill="x", padx=14, pady=(6, 4)) - self.hud_var = tk.StringVar(value="") - tk.Label( - ctrl_bar, - textvariable=self.hud_var, - font=("Georgia", 11, "bold"), - fg=ACCENT_GOLD, - bg=PANEL_BG, - ).pack(side="left") - self.status_var = tk.StringVar(value="") - tk.Label( - ctrl_bar, - textvariable=self.status_var, - font=("Helvetica", 9, "bold"), - fg=ACCENT_GOTH, - bg=PANEL_BG, - ).pack(side="left", padx=(14, 0)) - btn_box = tk.Frame(ctrl_bar, bg=PANEL_BG) - btn_box.pack(side="right") + # Untere Gothic-Leiste mit box_gold_double Rahmen unter dem Spielfeld + self.bottom_bar = SolitaireBottomBar(self.ctx.root, self.ctx, self.hud_var, self.status_var) + self.bottom_bar.pack(fill="x", side="bottom", padx=14, pady=(4, 10)) + + btn_norm = self.ctx.assets.raw_btn_default + btn_purp = self.ctx.assets.raw_btn_purple self.undo_btn = ImageButton( - btn_box, - t("sol_btn_undo"), - self.ctx.assets.raw_sel, - self.ctx.assets.raw_sel_active, - self._on_undo, - sound_mgr=self.ctx.sounds, - width=155, - height=32, - font=("Helvetica", 9, "bold"), - enabled=self.engine.can_undo, + self.bottom_bar, t("sol_btn_undo"), btn_norm, btn_purp, + self._on_undo, sound_mgr=self.ctx.sounds, width=136, height=32, + enabled=self.engine.can_undo, style="amethyst", ) - self.undo_btn.pack(side="left", padx=3) - self.undo_all_btn = ImageButton( - btn_box, - t("sol_btn_undo_all"), - self.ctx.assets.raw_sel, - self.ctx.assets.raw_sel_active, - self._on_undo_all, - sound_mgr=self.ctx.sounds, - width=108, - height=32, - font=("Helvetica", 9, "bold"), - enabled=self.engine.can_undo_all, + self.bottom_bar, t("sol_btn_undo_all"), btn_norm, btn_purp, + self._on_undo_all, sound_mgr=self.ctx.sounds, width=92, height=32, + enabled=self.engine.can_undo_all, style="amethyst", ) - self.undo_all_btn.pack(side="left", padx=3) - self.hint_btn = ImageButton( - btn_box, - t("sol_btn_hint"), - self.ctx.assets.raw_sel, - self.ctx.assets.raw_sel_active, - self._on_hint, - sound_mgr=self.ctx.sounds, - width=105, - height=32, - font=("Helvetica", 9, "bold"), - enabled=not self.engine.won, + self.bottom_bar, t("sol_btn_hint"), btn_norm, btn_purp, + self._on_hint, sound_mgr=self.ctx.sounds, width=92, height=32, + enabled=not self.engine.won, style="amethyst", ) - self.hint_btn.pack(side="left", padx=3) - self.new_btn = ImageButton( - btn_box, + self.bottom_bar, t("sol_btn_forfeit") if self.engine.moves > 0 else t("sol_btn_new_deal"), - self.ctx.assets.raw_sel, - self.ctx.assets.raw_sel_active, - self._on_new_or_forfeit_clicked, - sound_mgr=self.ctx.sounds, - width=115, - height=32, - font=("Helvetica", 9, "bold"), + btn_norm, btn_purp, self._on_new_or_forfeit_clicked, + sound_mgr=self.ctx.sounds, width=104, height=32, style="amethyst", ) - self.new_btn.pack(side="left", padx=(3, 0)) + self.bottom_bar.set_buttons([ + self.undo_btn, self.undo_all_btn, self.hint_btn, self.new_btn + ]) - self.canvas = tk.Canvas( - self.ctx.root, - bg=TABLE_BG, - highlightthickness=1, - highlightbackground=SUBTLE_BORDER, - ) - self.canvas.pack(fill="both", expand=True, padx=14, pady=(2, 12)) + self.canvas = tk.Canvas(self.ctx.root, bg=TABLE_BG, bd=0, highlightthickness=0) + self.canvas.pack(fill="both", expand=True, padx=14, pady=(4, 2)) self.animator = CardFlightAnimator(self.ctx.root, self.canvas) self.canvas.bind("", self._on_canvas_configure) @@ -432,9 +372,6 @@ class SpiderTableView: return Database.save_game_state(pid, GAME_FOLDER_ID, self.variant_key, self.engine.to_json()) - # ========================================================================= - # Uhr, stiller Zeit-Checkpoint & HUD - # ========================================================================= def _start_clock(self): if not self._canvas_alive(): return @@ -459,9 +396,10 @@ class SpiderTableView: elapsed_str = Database.format_seconds(self.engine.get_elapsed_seconds()) paused_tag = t("sol_hud_paused_tag") if (self.engine.is_timer_paused and not self.engine.won) else "" diff_label = t(f"sol_diff_short_{self.difficulty}") - base_txt = t("sol_hud_stats", self.engine.score, self.engine.moves, elapsed_str, paused_tag, diff_label) - extra_txt = t("sp_hud_extra", len(self.engine.completed_runs), self.engine.deals_remaining) - self.hud_var.set(base_txt + extra_txt) + new_hud = t("sol_hud_stats", self.engine.score, self.engine.moves, elapsed_str, paused_tag, diff_label) + # Nur schreiben, wenn sich der Text tatsächlich geändert hat! + if self.hud_var.get() != new_hud: + self.hud_var.set(new_hud) except Exception: pass @@ -473,18 +411,12 @@ class SpiderTableView: self.undo_all_btn.set_enabled((not locked) and self.engine.can_undo_all) self.hint_btn.set_enabled(not locked) new_lbl = t("sol_btn_forfeit") if (self.engine.moves > 0 and not self.engine.won) else t("sol_btn_new_deal") - if hasattr(self.new_btn, "set_text"): - self.new_btn.set_text(new_lbl) - elif hasattr(self.new_btn, "configure"): - try: - self.new_btn.configure(text=new_lbl) - except Exception: - pass + prev_w = self.new_btn.pixel_width + self.new_btn.set_text(new_lbl) + if self.new_btn.pixel_width != prev_w: + self.bottom_bar.relayout() self._update_hud_text() - # ========================================================================= - # Kartenpositions-Berechnung & Animations-Helfer (104 eindeutige Karten) - # ========================================================================= @staticmethod def _card_key(card: SolitaireCard) -> tuple[str, str, int]: return (card.suit, card.rank, card.deck_id) @@ -496,7 +428,6 @@ class SpiderTableView: canvas_h = max(440, self.canvas.winfo_height()) avail_h = max(180, canvas_h - self._tableau_y - self._frame_bot_pad) - down_cnt = sum(1 for c in cards if not c.face_up) up_cnt = max(0, len(cards) - down_cnt - 1) down_dy = max(6, int(ch * 0.088)) @@ -523,22 +454,18 @@ class SpiderTableView: def _snapshot_card_positions(self) -> dict[tuple[str, str, int], tuple[int, int]]: pos: dict[tuple[str, str, int], tuple[int, int]] = {} - # 1. Nachzieh-Pakete oben links (Spalte 0..1 gefächert) num_packs = len(self.engine.stock_deals) for p_idx, pack in enumerate(self.engine.stock_deals): - # Das nächste zu ziehende Paket (Index 0) liegt optisch ganz rechts oben auf dem Stapel visual_slot = (num_packs - 1) - p_idx px = self._stock_pack_x(visual_slot) for c in pack: pos[self._card_key(c)] = (px, self._top_y) - # 2. Abgeschlossene Sequenzen oben rechts (Spalten 2..9) for r_idx, run in enumerate(self.engine.completed_runs): rx = self._col_x[2 + min(7, r_idx)] for c in run: pos[self._card_key(c)] = (rx, self._top_y) - # 3. 10 Tableau-Spalten for col_idx in range(10): tx = self._col_x[col_idx] col = self.engine.tableau[col_idx] @@ -559,7 +486,6 @@ class SpiderTableView: if self._card_key(c) in moved_keys: ordered.append(c) for run in self.engine.completed_runs: - # König obenauf zeichnen, wenn eine fertige 13er-Sequenz nach oben fliegt for c in reversed(run): if self._card_key(c) in moved_keys: ordered.append(c) @@ -619,9 +545,6 @@ class SpiderTableView: self.animator.start(flights, self._draw_card_at, duration_ms=duration_ms, on_done=finish) return True - # ========================================================================= - # Ausgewogenes 10-Spalten-Layout & Rendering - # ========================================================================= def _on_canvas_configure(self, _event=None): if not self._canvas_alive(): return @@ -733,7 +656,6 @@ class SpiderTableView: font=("Georgia", 10, "bold"), fill=txt_c, tags=tags, ) - # Dezente Rahmenmarkierung für offene Karten, die wegen Farb-Bruch aktuell eingesperrt sind if dim_non_movable and card.face_up and not highlight_color: self.canvas.create_rectangle( x, y, x + cw, y + ch, @@ -757,7 +679,11 @@ class SpiderTableView: ): if not self._canvas_alive(): return - self.canvas.delete("all") + bg_ids = set(self.canvas.find_withtag("table_bg_slice")) + for item_id in self.canvas.find_all(): + if item_id not in bg_ids: + self.canvas.delete(item_id) + self._canvas_ui_refs.clear() cw, ch = self.card_size canvas_w = max(720, self.canvas.winfo_width()) canvas_h = max(440, self.canvas.winfo_height()) @@ -780,7 +706,7 @@ class SpiderTableView: hint = self._active_hint - # 1. Oben links (Spalte 0..1): 5 Nachzieh-Pakete als gestaffelter Fächer + # 1. Oben links (Spalte 0..1): Nachzieh-Pakete sx0 = self._col_x[0] stock_hl = ACCENT_GOLD if (hint and hint.get("type") == "deal_stock") else None vis_packs = [ @@ -812,7 +738,7 @@ class SpiderTableView: fill=ERROR_FG if (not can_deal_now) else ACCENT_GOLD, ) - # 2. Oben rechts (Spalten 2..9): 8 Ablage-Slots für vollendete König-bis-Ass-Sequenzen + # 2. Oben rechts (Spalten 2..9): 8 Ablage-Slots für vollendete Sequenzen for r_slot in range(8): rx = self._col_x[2 + r_slot] self._draw_slot(rx, self._top_y, symbol="♠", symbol_color=SUBTLE_BORDER) @@ -820,7 +746,6 @@ class SpiderTableView: run = self.engine.completed_runs[r_slot] vis_run = [c for c in run if self._card_key(c) not in hidden] if vis_run: - # König (Index 0 der Sequenz) thront repräsentativ oben auf dem fertigen Stapel self._draw_card_at(vis_run[0], rx, self._top_y, highlight_color=ACCENT_GOLD) # 3. Untere Reihe: 10 Tableau-Spalten @@ -855,7 +780,7 @@ class SpiderTableView: c_hl = None if is_last: if col_idx in valid_drag_same: - c_hl = ACCENT_GOLD # Gleichfarbiges Ziel glänzt golden! + c_hl = ACCENT_GOLD elif col_idx in valid_drag_mixed: c_hl = ACCENT_GOTH if hint: @@ -874,35 +799,26 @@ class SpiderTableView: next_y = ys[c_idx + 1] if not is_last else (cur_y + ch) self._tableau_card_rects[col_idx].append((tx, cur_y, tx + cw, next_y)) - # Pause-Banner nur anzeigen, wenn der Timer bereits aktiv gestartet wurde + # Pause-Banner mit box_purple + Old London if ( self.engine.has_timer_started and not self._window_active and not self.engine.won and self._modal_overlay is None ): - bw, bh = 430, 42 - bx = (canvas_w - bw) // 2 - by = canvas_h - bh - 12 - self.canvas.create_rectangle( - bx, by, bx + bw, by + bh, - fill=MODAL_BG, - outline=ACCENT_GOTH, - width=2, - ) - self.canvas.create_text( - bx + bw // 2, - by + bh // 2, - text=t("sol_canvas_paused_banner"), - font=("Helvetica", 10, "bold"), - fill=ACCENT_GOLD, + p_ph = self.ctx.assets.get_goth_text_photo( + t("sol_canvas_paused_banner"), FONT_SIZE_BODY, FONT_COLOR_TITLE_MAIN ) + bw, bh = p_ph.width() + 56, max(44, p_ph.height() + 18) + box_ph = self.ctx.assets.get_box_photo("box_purple", (bw, bh)) + self._canvas_ui_refs.extend([p_ph, box_ph] if box_ph else [p_ph]) + pcx, pcy = canvas_w // 2, canvas_h - bh // 2 - 18 + if box_ph: + self.canvas.create_image(pcx, pcy, image=box_ph, anchor="center") + self.canvas.create_image(pcx, pcy, image=p_ph, anchor="center") self._sync_buttons() - # ========================================================================= - # Hit-Testing & Maus-Steuerung (Timer startet erst bei echtem Treffer!) - # ========================================================================= def _hit_test(self, x: int, y: int) -> dict | None: sx1, sy1, sx2, sy2 = self._stock_bbox if sx1 <= x <= sx2 and sy1 <= y <= sy2: @@ -1067,12 +983,6 @@ class SpiderTableView: self._smart_auto_move(hit) def _smart_auto_move(self, info: dict): - """ - Intelligenter Doppelklick / Rechtsklick in Spider Solitaire: - 1. Bevorzugt gleichfarbige Zielkarte (z. B. Pik-7 auf Pik-8) - 2. Sonst passende andersfarbige Zielkarte (z. B. Pik-7 auf Herz-8) - 3. Sonst freie leere Spalte (sofern der Stapel nicht schon ganz alleine auf einer Spalte liegt) - """ if info.get("zone") != "tableau": return src_col = info["col"] @@ -1094,7 +1004,7 @@ class SpiderTableView: continue dst_pile = self.engine.tableau[dst_col] if not dst_pile: - if start_idx > 0: # Ganze Spalte in andere leere Spalte schieben vermeiden + if start_idx > 0: empty_targets.append(dst_col) elif dst_pile[-1].suit == head.suit: same_suit_targets.append(dst_col) @@ -1134,9 +1044,6 @@ class SpiderTableView: return self.engine.move_tableau_to_tableau(src_col, info["idx"], best_col) return False - # ========================================================================= - # Aktionen: Undo, Undo All, Deadlock-Check, Aufgeben & Sieg - # ========================================================================= def _after_player_move(self): self.status_var.set("") self._checkpoint_ticks = 0 @@ -1252,7 +1159,7 @@ class SpiderTableView: ) updated = Database.adjust_game_points(pid, GAME_FOLDER_ID, -penalty, min_floor_xp=floor_xp) deducted = max(0, prog["total_points"] - updated["total_points"]) - self.ctx.refresh_game_progress() + self.topbar.level_label.configure(text="") self.ctx.sounds.play("lose") if self._modal_overlay is not None: @@ -1277,39 +1184,6 @@ class SpiderTableView: self._save_progress() penalty = self._compute_forfeit_penalty() - overlay = tk.Frame( - self.ctx.root, - bg=MODAL_BG, - padx=28, - pady=22, - highlightthickness=2, - highlightbackground=ACCENT_GOTH, - ) - overlay.place(relx=0.5, rely=0.52, anchor="center") - self._modal_overlay = overlay - self._sync_buttons() - - tk.Label( - overlay, - text=t("sol_deadlock_title"), - font=("Georgia", 15, "bold"), - fg=ERROR_FG, - bg=MODAL_BG, - ).pack(pady=(0, 8)) - - tk.Label( - overlay, - text=t("sol_deadlock_desc", penalty), - font=("Helvetica", 10), - fg=FG_COLOR, - bg=MODAL_BG, - wraplength=460, - justify="center", - ).pack(pady=(0, 18)) - - row = tk.Frame(overlay, bg=MODAL_BG) - row.pack() - def undo_step(): self._close_active_modal() self._on_undo() @@ -1318,117 +1192,37 @@ class SpiderTableView: self._close_active_modal() self._on_undo_all() - ImageButton( - row, - t("sol_deadlock_btn_undo"), - self.ctx.assets.raw_btn, - self.ctx.assets.raw_btn_active, - undo_step, - sound_mgr=self.ctx.sounds, - width=170, - height=36, - font=("Helvetica", 9, "bold"), - enabled=self.engine.can_undo, - ).pack(side="left", padx=5) - - ImageButton( - row, - t("sol_deadlock_btn_undo_all"), - self.ctx.assets.raw_btn, - self.ctx.assets.raw_btn_active, - undo_everything, - sound_mgr=self.ctx.sounds, - width=175, - height=36, - font=("Helvetica", 9, "bold"), - enabled=self.engine.can_undo_all, - ).pack(side="left", padx=5) - - ImageButton( - row, - t("sol_deadlock_btn_end", penalty), - self.ctx.assets.raw_sel, - self.ctx.assets.raw_sel_active, - lambda: self._execute_forfeit(penalty, go_menu=True), - sound_mgr=self.ctx.sounds, - width=165, - height=36, - font=("Helvetica", 9, "bold"), - ).pack(side="left", padx=5) + self._modal_overlay = SolitaireModalDialog( + self.ctx, + title_txt=t("sol_deadlock_title"), + body_txt=t("sol_deadlock_desc", penalty), + is_danger=True, + buttons=[ + (t("sol_deadlock_btn_undo"), "fire", undo_step, self.engine.can_undo), + (t("sol_deadlock_btn_undo_all"), "fire", undo_everything, self.engine.can_undo_all), + (t("sol_deadlock_btn_end", penalty), "amethyst", lambda: self._execute_forfeit(penalty, go_menu=True), True), + ], + ) + self._sync_buttons() def _show_forfeit_modal(self): self.engine.pause_timer() self._save_progress() penalty = self._compute_forfeit_penalty() - overlay = tk.Frame( - self.ctx.root, - bg=MODAL_BG, - padx=28, - pady=22, - highlightthickness=2, - highlightbackground=ERROR_FG, + + self._modal_overlay = SolitaireModalDialog( + self.ctx, + title_txt=t("sol_forfeit_title"), + body_txt=t("sol_forfeit_desc", penalty), + is_danger=True, + buttons=[ + (t("sol_btn_cancel"), "amethyst", self._close_active_modal), + (t("sol_forfeit_confirm_new"), "fire", lambda: self._execute_forfeit(penalty, go_menu=False)), + (t("sol_forfeit_confirm_menu"), "amethyst", lambda: self._execute_forfeit(penalty, go_menu=True)), + ], ) - overlay.place(relx=0.5, rely=0.52, anchor="center") - self._modal_overlay = overlay self._sync_buttons() - tk.Label( - overlay, - text=t("sol_forfeit_title"), - font=("Georgia", 15, "bold"), - fg=ERROR_FG, - bg=MODAL_BG, - ).pack(pady=(0, 8)) - - tk.Label( - overlay, - text=t("sol_forfeit_desc", penalty), - font=("Helvetica", 10), - fg=FG_COLOR, - bg=MODAL_BG, - wraplength=430, - justify="center", - ).pack(pady=(0, 18)) - - row = tk.Frame(overlay, bg=MODAL_BG) - row.pack() - - ImageButton( - row, - t("sol_btn_cancel"), - self.ctx.assets.raw_sel, - self.ctx.assets.raw_sel_active, - self._close_active_modal, - sound_mgr=self.ctx.sounds, - width=145, - height=34, - font=("Helvetica", 9, "bold"), - ).pack(side="left", padx=5) - - ImageButton( - row, - t("sol_forfeit_confirm_new"), - self.ctx.assets.raw_btn, - self.ctx.assets.raw_btn_active, - lambda: self._execute_forfeit(penalty, go_menu=False), - sound_mgr=self.ctx.sounds, - width=175, - height=34, - font=("Helvetica", 9, "bold"), - ).pack(side="left", padx=5) - - ImageButton( - row, - t("sol_forfeit_confirm_menu"), - self.ctx.assets.raw_sel, - self.ctx.assets.raw_sel_active, - lambda: self._execute_forfeit(penalty, go_menu=True), - sound_mgr=self.ctx.sounds, - width=175, - height=34, - font=("Helvetica", 9, "bold"), - ).pack(side="left", padx=5) - def _handle_victory(self): self._game_concluded = True pid = self.ctx.profile["id"] @@ -1436,7 +1230,6 @@ class SpiderTableView: dur = self.engine.get_elapsed_seconds() prog = Database.get_game_progress(pid, GAME_FOLDER_ID) - # 104 Karten dauern länger als Klondike -> Speed-Bonus ab <= 6:00 bzw. <= 10:00 Min speed_bonus = 1.25 if dur <= 360 else (1.12 if dur <= 600 else 1.0) xp_earned = Progression.calculate_match_xp( prog["level"], @@ -1452,88 +1245,26 @@ class SpiderTableView: duration_sec=dur, points_gained=xp_earned, ) - self.ctx.refresh_game_progress() + self.topbar.level_label.configure(text="") self.ctx.sounds.play("win") self._show_victory_modal(xp_earned, old_lvl, new_lvl, dur) def _show_victory_modal(self, xp_earned: int, old_lvl: int, new_lvl: int, dur: float): - overlay = tk.Frame( - self.ctx.root, - bg=MODAL_BG, - padx=30, - pady=24, - highlightthickness=2, - highlightbackground=ACCENT_GOLD, - ) - overlay.place(relx=0.5, rely=0.52, anchor="center") - self._modal_overlay = overlay - self._sync_buttons() - - frames = self.ctx.assets.get_gif_frames("win_gif") - if frames: - gif_lbl = tk.Label(overlay, bg=MODAL_BG, image=frames[0]) - gif_lbl.pack(pady=(0, 10)) - - def anim(idx: int = 0): - if not self._canvas_alive() or self._modal_overlay is None: - return - gif_lbl.configure(image=frames[idx % len(frames)]) - self._gif_job = self.ctx.root.after(90, lambda: anim(idx + 1)) - - if len(frames) > 1: - anim(0) - - tk.Label( - overlay, - text=t("sol_win_title"), - font=("Georgia", 16, "bold"), - fg=ACCENT_GOLD, - bg=MODAL_BG, - ).pack(pady=(0, 6)) - - tk.Label( - overlay, - text=t( + lines = [ + t( "sol_win_summary", self.engine.score, self.engine.moves, Database.format_seconds(dur), t(f"sol_diff_short_{self.difficulty}"), ), - font=("Helvetica", 11), - fg=FG_COLOR, - bg=MODAL_BG, - ).pack(pady=(0, 8)) - - tk.Label( - overlay, - text=t("bj_popup_xp_earned", xp_earned), - font=("Helvetica", 11, "bold"), - fg=ACCENT_GOTH, - bg=MODAL_BG, - ).pack(pady=(0, 6)) - + t("bj_popup_xp_earned", xp_earned), + ] if new_lvl > old_lvl: - tk.Label( - overlay, - text=t("bj_popup_level_up", new_lvl, Progression.get_prestige_title(new_lvl)), - font=("Georgia", 12, "bold"), - fg="#7be08a", - bg=MODAL_BG, - ).pack(pady=(2, 10)) - - btn_row = tk.Frame(overlay, bg=MODAL_BG) - btn_row.pack(pady=(12, 0)) + lines.append(t("bj_popup_level_up", new_lvl, Progression.get_prestige_title(new_lvl))) def play_again(): - if self._gif_job is not None: - try: - self.ctx.root.after_cancel(self._gif_job) - except Exception: - pass - self._gif_job = None - overlay.destroy() - self._modal_overlay = None + self._close_active_modal() self._game_concluded = False self.engine.new_game(variant_key=self.variant_key, difficulty=self.difficulty) self._check_window_focus() @@ -1547,26 +1278,14 @@ class SpiderTableView: if callable(self.on_back_to_menu): self.on_back_to_menu() - ImageButton( - btn_row, - t("sol_play_again_btn"), - self.ctx.assets.raw_btn, - self.ctx.assets.raw_btn_active, - play_again, - sound_mgr=self.ctx.sounds, - width=175, - height=36, - font=("Helvetica", 10, "bold"), - ).pack(side="left", padx=6) - - ImageButton( - btn_row, - t("bj_popup_to_menu_btn"), - self.ctx.assets.raw_sel, - self.ctx.assets.raw_sel_active, - to_menu, - sound_mgr=self.ctx.sounds, - width=175, - height=36, - font=("Helvetica", 9 if len(t("bj_popup_to_menu_btn")) > 18 else 10, "bold"), - ).pack(side="left", padx=6) \ No newline at end of file + self._modal_overlay = SolitaireModalDialog( + self.ctx, + title_txt=t("sol_win_title"), + body_txt="\n".join(lines), + gif_key="win_gif", + buttons=[ + (t("sol_play_again_btn"), "fire", play_again), + (t("bj_popup_to_menu_btn"), "amethyst", to_menu), + ], + ) + self._sync_buttons() \ No newline at end of file diff --git a/resources/code_res/game_constants.py b/resources/code_res/game_constants.py index aaf5e16..cb54a15 100644 --- a/resources/code_res/game_constants.py +++ b/resources/code_res/game_constants.py @@ -71,7 +71,7 @@ UI_IMAGES = { # Banner & Spieltische "title": "title.png", "general_table": "general_table.jpg", - "poker_table": "poker_table.jpg", + "poker_table": "poker_table.png", "game_icon_art": "game_icon.jpg", # Buttons (Normal, Amethyst-Hover, Feuer-Highlight) @@ -274,7 +274,7 @@ PK_MAX_BOTS = 5 PK_STARTING_GOLD = 1000 PK_BOT_TURN_DELAY_MS = 600 PK_STREET_DELAY_MS = 700 -PK_TABLE_IMAGE = "poker_table.jpg" +PK_TABLE_IMAGE = "poker_table.png" PK_VARIANTS = { "poker_holdem": { diff --git a/resources/images/background_horizontal.jpg b/resources/images/background_horizontal.jpg index c840cb9..01107b7 100644 Binary files a/resources/images/background_horizontal.jpg and b/resources/images/background_horizontal.jpg differ diff --git a/resources/images/background_vertical.jpg b/resources/images/background_vertical.jpg index b830088..566b870 100644 Binary files a/resources/images/background_vertical.jpg and b/resources/images/background_vertical.jpg differ diff --git a/resources/images/poker_table.png b/resources/images/poker_table.png new file mode 100644 index 0000000..bee9752 Binary files /dev/null and b/resources/images/poker_table.png differ diff --git a/view/assets_manager.py b/view/assets_manager.py index 90c2eb8..0aa25a9 100644 --- a/view/assets_manager.py +++ b/view/assets_manager.py @@ -3,8 +3,9 @@ from __future__ import annotations import re +import tkinter as tk from pathlib import Path -from PIL import Image, ImageDraw, ImageFont, ImageTk +from PIL import Image, ImageChops, ImageDraw, ImageFont, ImageTk from models.resource_manager import ResourceManager from resources.code_res.game_constants import ( @@ -25,7 +26,7 @@ from resources.code_res.game_constants import ( PLAYING_CARD_SIZE, ) -# Anteil der Ecke im hochauflösenden Quellbild (damit das komplette Eck-Ornament erfasst wird) +# Anteil der Ecke im hochauflösenden Quellbild (erfasst das volle Eck-Ornament) BOX_SOURCE_CORNER_RATIO = { "box_big": 0.16, "box_gold_small": 0.24, @@ -34,50 +35,94 @@ BOX_SOURCE_CORNER_RATIO = { "dropdown_box": 0.085, } -# Ziel-Eckgröße im UI: skaliert relativ zur Boxgröße herunter und deckelt die maximale Rahmendicke! +# Ziel-Eckgröße im UI: (relativer_anteil_an_kleinerer_zielkante, min_px, max_px) BOX_TARGET_CORNER_SPEC = { - # box_key: (relativer_anteil_an_kleinerer_zielkante, min_px, max_px) "box_big": (0.14, 18, 46), "box_gold_small": (0.22, 14, 34), "box_gold_double": (0.18, 12, 26), "box_purple": (0.18, 14, 32), - "dropdown_box": (0.10, 10, 18), # Sehr feiner Rahmen (10..18px statt ~82px!) + "dropdown_box": (0.10, 10, 18), } _ALL_CAPS_WORD_RE = re.compile(r"\b[A-ZÄÖÜ]{4,}\b") +def _clean_box_matte_fast(pil_img: Image.Image | None, hollow_center: bool = True) -> Image.Image | None: + """ + Entfernt opake schwarze JPEG-Ränder (und bei Rahmen-Boxen auch das schwarze Innenfeld) + komplett in C-Geschwindigkeit via ImageChops + ImageDraw.floodfill (< 1 ms). + """ + if pil_img is None: + return None + rgba = pil_img.convert("RGBA") + w, h = rgba.size + if w < 8 or h < 8: + return rgba + + r, g, b, a = rgba.split() + luma = ImageChops.lighter(ImageChops.lighter(r, g), b) + seed_img = luma.point(lambda p: 0 if p < 18 else 255) + + seeds = [(0, 0), (w - 1, 0), (0, h - 1), (w - 1, h - 1)] + if hollow_center: + seeds.append((w // 2, h // 2)) + + changed = False + for sx, sy in seeds: + if rgba.getpixel((sx, sy))[3] > 240 and seed_img.getpixel((sx, sy)) == 0: + ImageDraw.floodfill(seed_img, (sx, sy), 128) + changed = True + + if changed: + ext_alpha = seed_img.point(lambda p: 0 if p == 128 else 255) + rgba.putalpha(ImageChops.darker(a, ext_alpha)) + + return rgba + + class AssetManager: def __init__(self, root_dir: Path): self.root_dir = root_dir self.res = ResourceManager(root_dir) + # --- Caches --- + self._tk_cache: dict = {} + self._pil_cache: dict = {} + self._raw_card_cache: dict[str, Image.Image | None] = {} + self._font_cache: dict[tuple[bool, int], ImageFont.FreeTypeFont | ImageFont.ImageFont] = {} + self._bg_scaled_key: tuple[bool, int, int] | None = None + self._bg_scaled_pil: Image.Image | None = None + # --- Hintergründe & Spieltische --- self.raw_bg_horizontal = self._load_ui_flexible("bg_horizontal", "background_horizontal") self.raw_bg_vertical = self._load_ui_flexible("bg_vertical", "background_vertical") self.raw_bg = self.raw_bg_horizontal or self._load_ui_flexible("background", "background") self.raw_title = self._load_ui_flexible("title", "title") - self.raw_general_table = self._load_ui_flexible("general_table", "general_table") + self.raw_general_table = None self.raw_poker_table = self._load_ui_flexible("poker_table", "poker_table") - # --- Neue Buttons (Default, Amethyst-Hover, Feuer-Highlight) --- + # --- Buttons (Default, Amethyst-Hover, Feuer-Highlight) --- self.raw_btn_default = self._load_ui_flexible("btn_default", "button") self.raw_btn_purple = self._load_ui_flexible("btn_purple", "button_highlighted_purple") self.raw_btn_fire = self._load_ui_flexible("btn_fire", "button_highlighted_fire") - # Abwärtskompatible Aliase für bestehende Views: - self.raw_btn = self.raw_btn_fire or self.raw_btn_default - self.raw_btn_active = self.raw_btn_fire or self.raw_btn_purple - self.raw_sel = self.raw_btn_default - self.raw_sel_active = self.raw_btn_purple or self.raw_btn_default - - # --- Transparente Zierrahmen (9-Slice) --- + # --- Transparente Zierrahmen (9-Slice, einmalig beim Start in C freigestellt) --- self.raw_boxes: dict[str, Image.Image | None] = { - "box_big": self._load_ui_flexible("box_big", "box_big"), - "box_gold_small": self._load_ui_flexible("box_gold_small", "box_gold_smal", "box_gold_small"), - "box_gold_double": self._load_ui_flexible("box_gold_double", "box_gold_small_double"), - "box_purple": self._load_ui_flexible("box_purple", "box_small_purple"), - "dropdown_box": self._load_ui_flexible("dropdown_box", "dropdown_box"), + "box_big": _clean_box_matte_fast( + self._load_ui_flexible("box_big", "box_big"), hollow_center=True + ), + "box_gold_small": _clean_box_matte_fast( + self._load_ui_flexible("box_gold_small", "box_gold_smal", "box_gold_small"), hollow_center=True + ), + "box_gold_double": _clean_box_matte_fast( + self._load_ui_flexible("box_gold_double", "box_gold_small_double"), hollow_center=True + ), + "box_purple": _clean_box_matte_fast( + self._load_ui_flexible("box_purple", "box_small_purple"), hollow_center=True + ), + "dropdown_box": _clean_box_matte_fast( + self._load_ui_flexible("dropdown_box", "dropdown_box"), hollow_center=False + ), } self.raw_chat_frame = self.raw_boxes["box_big"] @@ -94,10 +139,14 @@ class AssetManager: self.raw_dropdown_box = self.raw_boxes["dropdown_box"] self.raw_dropdown_selection = self._load_ui_flexible("dropdown_selection", "dropdown_selection") - # --- Caches --- - self._tk_cache: dict = {} - self._pil_cache: dict = {} - self._font_cache: dict[tuple[bool, int], ImageFont.FreeTypeFont | ImageFont.ImageFont] = {} + # Einmaliges Screen-bewusstes Vorskalieren (behält 4K auf großen Screens, entlastet 1080p/Chromebook) + self._optimize_raw_for_display() + + # Abwärtskompatible Aliase nach evtl. Vorskalierung setzen + self.raw_btn = self.raw_btn_fire or self.raw_btn_default + self.raw_btn_active = self.raw_btn_fire or self.raw_btn_purple + self.raw_sel = self.raw_btn_default + self.raw_sel_active = self.raw_btn_purple or self.raw_btn_default @staticmethod def _load_pil(path: Path | None) -> Image.Image | None: @@ -109,10 +158,6 @@ class AssetManager: return None def _load_ui_flexible(self, ui_key: str, *stem_fallbacks: str) -> Image.Image | None: - """ - Versucht zuerst den Pfad aus UI_IMAGES via ResourceManager zu laden und prüft - anschließend Fallback-Dateinamen mit .png / .jpg / .jpeg in resources/images/. - """ try: p = self.res.get_ui_image_path(ui_key) pil = self._load_pil(p) @@ -131,6 +176,87 @@ class AssetManager: return loaded return None + def _optimize_raw_for_display(self): + """ + Hält auf 4K/Ultrawide (>= 2500px) die volle Originalauflösung, dampft aber auf + kleineren Displays (z. B. 1080p Chromebook) überdimensionierte Rohbilder einmalig vor. + """ + try: + r = tk._default_root + sw = r.winfo_screenwidth() if r else 1920 + sh = r.winfo_screenheight() if r else 1080 + except Exception: + sw, sh = 1920, 1080 + + # Button-Rohlinge müssen auf keinem Display höher als 160px sein (UI-Buttons sind 32..46px hoch) + btn_cap_h = 200 if max(sw, sh) >= 2500 else 130 + for attr in ("raw_btn_default", "raw_btn_purple", "raw_btn_fire"): + img = getattr(self, attr, None) + if img is not None and img.height > btn_cap_h: + ratio = btn_cap_h / img.height + nw = max(1, int(round(img.width * ratio))) + setattr(self, attr, img.resize((nw, btn_cap_h), Image.Resampling.LANCZOS)) + + if max(sw, sh) >= 2500: + return + + max_bg_w = int(sw * 1.15) + max_bg_h = int(sh * 1.15) + for attr in ("raw_bg_horizontal", "raw_bg_vertical", "raw_bg", "raw_poker_table"): + img = getattr(self, attr, None) + if img is not None and (img.width > max_bg_w or img.height > max_bg_h): + ratio = min(max_bg_w / img.width, max_bg_h / img.height) + nw = max(1, int(round(img.width * ratio))) + nh = max(1, int(round(img.height * ratio))) + setattr(self, attr, img.resize((nw, nh), Image.Resampling.LANCZOS)) + + # ------------------------------------------------------------------ + # ZENTRALER HINTERGRUND-CACHE (1x Resize für Topbar, Menüs & Tische) + # ------------------------------------------------------------------ + def get_window_bg_pil(self, rw: int, rh: int) -> Image.Image | None: + rw, rh = max(64, int(rw)), max(64, int(rh)) + is_vert = bool(rh > rw and self.raw_bg_vertical is not None) + key = (is_vert, rw, rh) + if key == self._bg_scaled_key and self._bg_scaled_pil is not None: + return self._bg_scaled_pil + + src = self.raw_bg_vertical if is_vert else (self.raw_bg_horizontal or self.raw_bg) + if src is None: + return None + + # RGB statt RGBA für den opaken Vollbild-Hintergrund spart 25% RAM & X11-Transferzeit + rgb_src = src.convert("RGB") if src.mode != "RGB" else src + self._bg_scaled_pil = rgb_src.resize((rw, rh), Image.Resampling.BILINEAR) + self._bg_scaled_key = key + return self._bg_scaled_pil + + def get_bg_patch_photo( + self, rw: int, rh: int, ox: int, oy: int, w: int, h: int + ) -> ImageTk.PhotoImage | None: + w, h = max(1, int(w)), max(1, int(h)) + rw, rh = max(w, int(rw)), max(h, int(rh)) + ox = max(0, min(rw - w, int(ox))) + oy = max(0, min(rh - h, int(oy))) + + tk_key = ("bg_patch", rw, rh, ox, oy, w, h) + if tk_key in self._tk_cache: + return self._tk_cache[tk_key] + + base = self.get_window_bg_pil(rw, rh) + if base is None: + return None + + # Ring-Cleanup für alte Fenstergrößen + if len(self._tk_cache) > 360: + stale = [k for k in self._tk_cache if isinstance(k, tuple) and k and k[0] == "bg_patch"] + for k in stale[:-12]: + self._tk_cache.pop(k, None) + + cropped = base.crop((ox, oy, ox + w, oy + h)) + photo = ImageTk.PhotoImage(cropped) + self._tk_cache[tk_key] = photo + return photo + # ------------------------------------------------------------------ # FONT-LOADER & OLD-LONDON TEXT-RENDERER (PIL RGBA) # ------------------------------------------------------------------ @@ -150,7 +276,6 @@ class AssetManager: @staticmethod def sanitize_goth_case(text: str) -> str: - """Verhindert unlesbare Fraktur-Versalienketten (z.B. 'GOLD-POT' -> 'Gold-Pot'), lässt Kürzel wie 'XP'/'DE' stehen.""" if not text or not FONT_FORCE_MIXED_CASE: return text return _ALL_CAPS_WORD_RE.sub(lambda m: m.group(0).capitalize(), text) @@ -164,12 +289,13 @@ class AssetManager: ) -> float: if not line: return 0.0 + if letter_spacing == 0: + return float(draw.textlength(line, font=font)) + adv_fn = draw.textlength total = 0.0 - for idx, ch in enumerate(line): - total += draw.textlength(ch, font=font) - if idx < len(line) - 1: - total += letter_spacing - return total + for ch in line: + total += adv_fn(ch, font=font) + return total + letter_spacing * (len(line) - 1) def _draw_tracked_line( self, @@ -183,15 +309,27 @@ class AssetManager: shadow_offset: tuple[int, int] | None, outline_px: int, ): + if not line: + return + has_shadow = bool(FONT_SHADOW_ENABLED and shadow_offset and (shadow_offset[0] or shadow_offset[1])) + sx = shadow_offset[0] if (has_shadow and shadow_offset) else 0 + sy = shadow_offset[1] if (has_shadow and shadow_offset) else 0 + + # C-Fast-Path ohne künstliches Letter-Spacing (1 einziger FreeType-Durchlauf für die ganze Zeile!) + if letter_spacing == 0: + if has_shadow: + draw.text((x + sx, y + sy), line, font=font, fill=FONT_SHADOW_COLOR) + if outline_px > 0: + draw.text((x, y), line, font=font, fill=fill, stroke_width=outline_px, stroke_fill=FONT_OUTLINE_COLOR) + else: + draw.text((x, y), line, font=font, fill=fill) + return + + adv_fn = draw.textlength cur_x = x for ch in line: - if FONT_SHADOW_ENABLED and shadow_offset and (shadow_offset[0] or shadow_offset[1]): - draw.text( - (cur_x + shadow_offset[0], y + shadow_offset[1]), - ch, - font=font, - fill=FONT_SHADOW_COLOR, - ) + if has_shadow: + draw.text((cur_x + sx, y + sy), ch, font=font, fill=FONT_SHADOW_COLOR) if outline_px > 0: draw.text( (cur_x, y), @@ -203,7 +341,7 @@ class AssetManager: ) else: draw.text((cur_x, y), ch, font=font, fill=fill) - cur_x += draw.textlength(ch, font=font) + letter_spacing + cur_x += adv_fn(ch, font=font) + letter_spacing def render_goth_text_pil( self, @@ -216,24 +354,20 @@ class AssetManager: outline_px: int = FONT_OUTLINE_THICKNESS_PX, letter_spacing: int = FONT_LETTER_SPACING_PX, alternate: bool = False, + uncached: bool = False, ) -> Image.Image: - """ - Rendert Old-London-Text als scharfes, transparentes RGBA-PIL-Bild ohne jegliches - Plattform-/Xft-Clipping an Ober- oder Unterlängen. - """ clean_text = self.sanitize_goth_case(str(text or "")) cache_key = ( "goth_txt_pil", clean_text, size_px, color, max_width, - align, shadow_offset, outline_px, letter_spacing, alternate + align, shadow_offset, outline_px, letter_spacing, alternate, ) - if cache_key in self._pil_cache: + if not uncached and cache_key in self._pil_cache: return self._pil_cache[cache_key] font = self.get_pil_font(size_px, alternate=alternate) dummy = Image.new("RGBA", (8, 8), (0, 0, 0, 0)) d_draw = ImageDraw.Draw(dummy) - # Automatischer Zeilenumbruch bei max_width raw_paragraphs = clean_text.split("\n") lines: list[str] = [] for para in raw_paragraphs: @@ -285,7 +419,12 @@ class AssetManager: draw, lx, ly, ln, font, color, letter_spacing, shadow_offset, outline_px ) - self._pil_cache[cache_key] = canvas_img + if not uncached: + if len(self._pil_cache) > 500: + txt_keys = [k for k in self._pil_cache if isinstance(k, tuple) and k and k[0] == "goth_txt_pil"] + for k in txt_keys[:150]: + self._pil_cache.pop(k, None) + self._pil_cache[cache_key] = canvas_img return canvas_img def get_goth_text_photo( @@ -302,7 +441,7 @@ class AssetManager: ) -> ImageTk.PhotoImage: tk_key = ( "goth_txt_tk", text, size_px, color, max_width, - align, shadow_offset, outline_px, letter_spacing, alternate + align, shadow_offset, outline_px, letter_spacing, alternate, ) if tk_key not in self._tk_cache: pil_img = self.render_goth_text_pil( @@ -316,12 +455,13 @@ class AssetManager: letter_spacing=letter_spacing, alternate=alternate, ) + if len(self._tk_cache) > 500: + txt_keys = [k for k in self._tk_cache if isinstance(k, tuple) and k and k[0] == "goth_txt_tk"] + for k in txt_keys[:150]: + self._tk_cache.pop(k, None) self._tk_cache[tk_key] = ImageTk.PhotoImage(pil_img) return self._tk_cache[tk_key] - # ------------------------------------------------------------------ - # 9-SLICE RAHMEN-SCALER FÜR TRANSPARENTE BOXEN (box_*.png) - # ------------------------------------------------------------------ # ------------------------------------------------------------------ # 9-SLICE RAHMEN-SCALER FÜR TRANSPARENTE BOXEN (fein herunterskaliert!) # ------------------------------------------------------------------ @@ -332,10 +472,6 @@ class AssetManager: corner_ratio: float | None = None, border_scale: float = 1.0, ) -> Image.Image | None: - """ - Skaliert einen hochauflösenden Zierrahmen per 9-Slice proportional zur Zielgröße - herunter, sodass Rahmen & Ecken fein bleiben statt klobig zu wirken. - """ src = self.raw_boxes.get(box_key) tw, th = max(16, int(target_size[0])), max(16, int(target_size[1])) if src is None: @@ -347,23 +483,21 @@ class AssetManager: return self._pil_cache[pil_key] sw, sh = src.size - # 1. Quell-Ausschnitt der Ecke im Originalbild (erfasst das volle Eck-Ornament) sc = max(12, int(round(min(sw, sh) * src_ratio))) - # 2. Ziel-Größe der Ecke im UI relativ zur Boxgröße klein halten (herunterskalieren!) rel_target, min_dc, max_dc = BOX_TARGET_CORNER_SPEC.get(box_key, (0.14, 12, 36)) scaled_dc = int(round(min(tw, th) * rel_target * border_scale)) dc = max(min_dc, min(max_dc, scaled_dc)) dc = min(dc, sc, tw // 2 - 1, th // 2 - 1) if dc < 6: - out = src.resize((tw, th), Image.Resampling.LANCZOS) + out = src.resize((tw, th), Image.Resampling.BILINEAR) self._pil_cache[pil_key] = out return out out = Image.new("RGBA", (tw, th), (0, 0, 0, 0)) - # 4 Ecken sauber mit LANCZOS herunterskalieren + # 4 Ecken sauber mit LANCZOS herunterskalieren, gerade Kanten schnell mit BILINEAR tl = src.crop((0, 0, sc, sc)).resize((dc, dc), Image.Resampling.LANCZOS) tr = src.crop((sw - sc, 0, sw, sc)).resize((dc, dc), Image.Resampling.LANCZOS) bl = src.crop((0, sh - sc, sc, sh)).resize((dc, dc), Image.Resampling.LANCZOS) @@ -374,23 +508,20 @@ class AssetManager: out.paste(bl, (0, th - dc)) out.paste(br, (tw - dc, th - dc)) - # Obere & untere Kante (Dicke = dc -> exakt passend zu den verkleinerten Ecken!) mid_w = tw - 2 * dc if mid_w > 0: - top_edge = src.crop((sc, 0, sw - sc, sc)).resize((mid_w, dc), Image.Resampling.LANCZOS) - bot_edge = src.crop((sc, sh - sc, sw - sc, sh)).resize((mid_w, dc), Image.Resampling.LANCZOS) + top_edge = src.crop((sc, 0, sw - sc, sc)).resize((mid_w, dc), Image.Resampling.BILINEAR) + bot_edge = src.crop((sc, sh - sc, sw - sc, sh)).resize((mid_w, dc), Image.Resampling.BILINEAR) out.paste(top_edge, (dc, 0)) out.paste(bot_edge, (dc, th - dc)) - # Linke & rechte Kante (Breite = dc) mid_h = th - 2 * dc if mid_h > 0: - left_edge = src.crop((0, sc, sc, sh - sc)).resize((dc, mid_h), Image.Resampling.LANCZOS) - right_edge = src.crop((sw - sc, sc, sw, sh - sc)).resize((dc, mid_h), Image.Resampling.LANCZOS) + left_edge = src.crop((0, sc, sc, sh - sc)).resize((dc, mid_h), Image.Resampling.BILINEAR) + right_edge = src.crop((sw - sc, sc, sw, sh - sc)).resize((dc, mid_h), Image.Resampling.BILINEAR) out.paste(left_edge, (0, dc)) out.paste(right_edge, (tw - dc, dc)) - # Mittelstück bei dropdown_box.png füllen if mid_w > 0 and mid_h > 0 and box_key == "dropdown_box": center_patch = src.crop((sc, sc, sw - sc, sh - sc)).resize((mid_w, mid_h), Image.Resampling.BILINEAR) out.paste(center_patch, (dc, dc)) @@ -413,37 +544,41 @@ class AssetManager: if pil_box is not None: self._tk_cache[tk_key] = ImageTk.PhotoImage(pil_box) return self._tk_cache.get(tk_key) - - def get_box_photo( - self, - box_key: str, - size: tuple[int, int], - corner_ratio: float | None = None, - ) -> ImageTk.PhotoImage | None: - tk_key = ("9slice_tk", box_key, size, corner_ratio) - if tk_key not in self._tk_cache: - pil_box = self.get_9slice_pil(box_key, size, corner_ratio=corner_ratio) - if pil_box is not None: - self._tk_cache[tk_key] = ImageTk.PhotoImage(pil_box) - return self._tk_cache.get(tk_key) # ------------------------------------------------------------------ - # KARTEN, BANNER & GIFS + # KARTEN, BANNER & GIFS (Punkt 4: Vorgedampfter Rohkarten-Cache!) # ------------------------------------------------------------------ + def _get_raw_card_pil(self, path: Path | None) -> Image.Image | None: + """ + Lädt jede Spielkarte nur EINMALIG von der Platte und dampft riesige Vorlagen + mit LANCZOS auf max. 340px Breite vor (reicht selbst für 4K-Spieltische locker aus + und beschleunigt alle anschließenden Karten-Resizes um den Faktor ~5x!). + """ + if not path: + return None + key = str(path) + if key not in self._raw_card_cache: + pil = self._load_pil(path) + if pil is not None and pil.width > 340: + nh = max(1, int(round(pil.height * (340.0 / pil.width)))) + pil = pil.resize((340, nh), Image.Resampling.LANCZOS) + self._raw_card_cache[key] = pil + return self._raw_card_cache[key] + def get_card_photo(self, card_filename: str, size=PLAYING_CARD_SIZE) -> ImageTk.PhotoImage | None: key = ("card", self.res.card_theme, card_filename, size) if key not in self._tk_cache: - pil = self._load_pil(self.res.get_card_path(card_filename)) + pil = self._get_raw_card_pil(self.res.get_card_path(card_filename)) if pil: - self._tk_cache[key] = ImageTk.PhotoImage(pil.resize(size, Image.Resampling.LANCZOS)) + self._tk_cache[key] = ImageTk.PhotoImage(pil.resize(size, Image.Resampling.BILINEAR)) return self._tk_cache.get(key) def get_card_back_photo(self, color: str = "Black", size=PLAYING_CARD_SIZE) -> ImageTk.PhotoImage | None: key = ("card_back", self.res.card_theme, color, size) if key not in self._tk_cache: - pil = self._load_pil(self.res.get_card_back_path(color)) + pil = self._get_raw_card_pil(self.res.get_card_back_path(color)) if pil: - self._tk_cache[key] = ImageTk.PhotoImage(pil.resize(size, Image.Resampling.LANCZOS)) + self._tk_cache[key] = ImageTk.PhotoImage(pil.resize(size, Image.Resampling.BILINEAR)) return self._tk_cache.get(key) def get_scaled_photo(self, name: str, pil_img, size: tuple[int, int]) -> ImageTk.PhotoImage | None: @@ -455,7 +590,6 @@ class AssetManager: return self._tk_cache[key] def get_proportional_photo(self, name: str, pil_img, target_width: int) -> ImageTk.PhotoImage | None: - """Skaliert ein Banner (z.B. title.jpg) exakt im Original-Seitenverhältnis auf target_width.""" if not pil_img or target_width <= 10: return None src_w, src_h = pil_img.size @@ -472,7 +606,7 @@ class AssetManager: with Image.open(path) as gif: idx = 0 while True: - frame = gif.copy().convert("RGBA").resize(size, Image.Resampling.LANCZOS) + frame = gif.copy().convert("RGBA").resize(size, Image.Resampling.BILINEAR) frames.append(ImageTk.PhotoImage(frame)) idx += 1 gif.seek(idx) @@ -481,4 +615,86 @@ class AssetManager: except Exception: pass self._tk_cache[cache_key] = frames - return self._tk_cache[cache_key] \ No newline at end of file + return self._tk_cache[cache_key] + + # ------------------------------------------------------------------ + # STARTUP-PRELOADER: Lädt Karten, Fonts, Boxen & Standard-Buttons vorab + # ------------------------------------------------------------------ + def preload_startup_assets(self, init_win_size: tuple[int, int] = (1280, 760), on_step=None): + """ + Wird einmalig beim Programmstart aufgerufen, damit im laufenden Betrieb + (z. B. beim Erstellen von Goldbeuteln, Menüwechseln oder Spielstart) + keinerlei Disk-I/O oder Erst-Dekodierung mehr blockiert. + """ + from resources.code_res.game_constants import SUITS, RANKS + from resources.code_res.i18n import t + from view.widgets.image_button import ImageButton, _trim_button_art + from view.widgets.goth_dropdown import _trim_outer_black_bbox + + def _notify(msg: str): + if callable(on_step): + on_step(msg) + + # 1. Alle genutzten Font-Größen in FreeType vorwärmen + _notify("Fonts...") + for px in (14, 15, 16, 18, 20, 22, 24, 26, 30, 34, 38): + self.get_pil_font(px, alternate=False) + + # 2. Fenster-Hintergrund für Startgröße vorberechnen + _notify("Background...") + w, h = max(800, init_win_size[0]), max(600, init_win_size[1]) + self.get_bg_patch_photo(w, h, 0, 0, w, h) + if self.raw_title is not None: + self.get_proportional_photo("title_main_header", self.raw_title, 265) + + # 3. Button- & Dropdown-Rohlinge vorab trimmen + Topbar-Standardbuttons cachen + _notify("UI Controls...") + for raw_b in (self.raw_btn_default, self.raw_btn_purple, self.raw_btn_fire): + if raw_b is not None: + _trim_button_art(raw_b) + + for raw_dd in ( + self.raw_dropdown_closed, + self.raw_dropdown_closed_btn, + self.raw_dropdown_open, + self.raw_dropdown_open_btn, + ): + if raw_dd is not None: + _trim_outer_black_bbox(raw_dd) + + # Häufigste Topbar-Buttons im globalen _BTN_PHOTO_CACHE vorbacken + dummy_root = tk._default_root + if dummy_root is not None and self.raw_btn_default is not None: + common_specs = [ + (t("btn_back_main"), 110, 32), + (t("btn_back_game_menu"), 108, 32), + (t("btn_stats"), 96, 32), + (t("btn_lang"), 96, 32), + (t("btn_audio"), 76, 32), + (t("btn_switch_profile"), 124, 34), + ] + for lbl, bw, bh in common_specs: + tmp = ImageButton( + dummy_root, lbl, self.raw_btn_default, self.raw_btn_purple, + None, width=bw, height=bh, style="amethyst" + ) + tmp._ensure_hover() + tmp.destroy() + + # 4. Komplette 52er Kartendecks + Kartenrücken einmalig von Disk in _raw_card_cache laden + _notify("Cards...") + for suit in SUITS: + for rank in RANKS: + fname = f"{rank}_of_{suit}.png" + p = self.res.get_card_path(fname) + if p and p.is_file(): + self._get_raw_card_pil(p) + for back_col in ("Black", "Red", "Blue", "Purple", "Gold"): + bp = self.res.get_card_back_path(back_col) + if bp and bp.is_file(): + self._get_raw_card_pil(bp) + + # 5. Ergebnis-GIFs vorab dekodieren + _notify("Animations...") + for gif_key in ("win_gif", "lose_gif", "draw_gif"): + self.get_gif_frames(gif_key) \ No newline at end of file diff --git a/view/main_window.py b/view/main_window.py index 7d1f719..39c16a8 100644 --- a/view/main_window.py +++ b/view/main_window.py @@ -38,6 +38,8 @@ class GothCardCollectionView(tk.Tk): self.protocol("WM_DELETE_WINDOW", self.close_app) self.assets = AssetManager(root_dir) + self.update_idletasks() + self.assets.preload_startup_assets((self.winfo_width(), self.winfo_height())) self.bg_widget = None self.login_view = LoginView(self) self.main_menu_view = MainMenuView(self) @@ -134,18 +136,27 @@ class GothCardCollectionView(tk.Tk): self.destroy() # Unten in GothCardCollectionView (view/main_window.py): - def clear_window(self, apply_global_bg=True): - self.bg_widget = None - for widget in self.winfo_children(): - widget.destroy() - if apply_global_bg and (self.assets.raw_bg_horizontal or self.assets.raw_bg): - self.bg_widget = ResizingBG( - self, - self.assets.raw_bg_horizontal or self.assets.raw_bg, - pil_vertical=self.assets.raw_bg_vertical, - bg=BG_COLOR, - ) - self.bg_widget.place(relx=0, rely=0, relwidth=1, relheight=1) + def clear_window(self, apply_global_bg: bool = True): + bg = getattr(self, "bg_widget", None) + + if apply_global_bg and (bg is None or not bg.winfo_exists()): + from view.widgets.resizing_bg import ResizingBG + self.bg_widget = ResizingBG(self, self.assets) + self.bg_widget.place(x=0, y=0, relwidth=1, relheight=1) + bg = self.bg_widget + + for child in list(self.winfo_children()): + if child is bg: + continue + try: + child.destroy() + except Exception: + pass + + if bg is not None and bg.winfo_exists(): + bg.clear_foreground() + if apply_global_bg: + tk.Misc.lower(bg) def show_login(self, profiles: list[str], preselect_name: str = ""): self.login_view.show(profiles, preselect_name) diff --git a/view/menus/__pycache__/main_menu_view.cpython-311.pyc b/view/menus/__pycache__/main_menu_view.cpython-311.pyc index 80e6b8f..08f6f15 100644 Binary files a/view/menus/__pycache__/main_menu_view.cpython-311.pyc and b/view/menus/__pycache__/main_menu_view.cpython-311.pyc differ diff --git a/view/widgets/__pycache__/image_button.cpython-311.pyc b/view/widgets/__pycache__/image_button.cpython-311.pyc index 1d1d0ad..60ae77e 100644 Binary files a/view/widgets/__pycache__/image_button.cpython-311.pyc and b/view/widgets/__pycache__/image_button.cpython-311.pyc differ diff --git a/view/widgets/goth_dropdown.py b/view/widgets/goth_dropdown.py index 9880963..8e12ef1 100644 --- a/view/widgets/goth_dropdown.py +++ b/view/widgets/goth_dropdown.py @@ -3,7 +3,7 @@ from __future__ import annotations import tkinter as tk -from PIL import Image, ImageDraw, ImageEnhance, ImageTk +from PIL import Image, ImageDraw, ImageEnhance, ImageTk, ImageChops from resources.code_res.game_constants import ( BG_COLOR, @@ -30,40 +30,18 @@ _TRIM_CACHE: dict[tuple[int, int, int], Image.Image] = {} def _trim_outer_black_bbox(pil_img: Image.Image, threshold: int = 38) -> Image.Image: - """ - Schneidet äußere schwarze Leerränder exakt bis zur eigentlichen Rahmenkante ab, - damit linkes Hauptstück und rechtes Button-Stück ohne Höhenversatz nahtlos aneinanderpassen. - """ - key = (id(pil_img), pil_img.width, pil_img.height) + """C-beschleunigtes Trimmen schwarzer Außenränder via Pillow Lookup-Table (< 1 ms).""" + key = (id(pil_img), pil_img.width, pil_img.height, threshold) if key in _TRIM_CACHE: return _TRIM_CACHE[key] clean = _clean_outer_black_matte(pil_img) - rgb = clean.convert("RGB") - w, h = rgb.size - px = rgb.load() + r, g, b, _a = clean.split() + max_rgb = ImageChops.lighter(ImageChops.lighter(r, g), b) + mask = max_rgb.point(lambda p: 255 if p > threshold else 0) + bbox = mask.getbbox() - min_x, min_y = w, h - max_x, max_y = -1, -1 - - for y in range(h): - for x in range(w): - r, g, b = px[x, y] - if r > threshold or g > threshold or b > threshold: - if x < min_x: - min_x = x - if x > max_x: - max_x = x - if y < min_y: - min_y = y - if y > max_y: - max_y = y - - if max_x <= min_x or max_y <= min_y: - _TRIM_CACHE[key] = clean - return clean - - cropped = clean.crop((min_x, min_y, max_x + 1, max_y + 1)) + cropped = clean.crop(bbox) if bbox else clean _TRIM_CACHE[key] = cropped return cropped diff --git a/view/widgets/image_button.py b/view/widgets/image_button.py index cc98299..0d3099c 100644 --- a/view/widgets/image_button.py +++ b/view/widgets/image_button.py @@ -5,7 +5,7 @@ from __future__ import annotations import re from pathlib import Path import tkinter as tk -from PIL import Image, ImageDraw, ImageEnhance, ImageFont, ImageTk +from PIL import Image, ImageDraw, ImageEnhance, ImageFont, ImageTk, ImageChops from resources.code_res.game_constants import ( BG_COLOR, @@ -35,9 +35,11 @@ _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] = {} -_LEADING_ICON_RE = re.compile(r"^(?:[←→↑↓↔❖†•✦★☆▶◀«»]+|\+(?=\s))\s*") -_TRAILING_ICON_RE = re.compile(r"\s*[←→↑↓↔❖†•✦★☆▶◀«»]+$") +# Entfernt alle vorangestellten/nachgestellten 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) @@ -56,40 +58,31 @@ def _get_old_london(size_px: int) -> ImageFont.FreeTypeFont | ImageFont.ImageFon def _clean_outer_black_matte(pil_img: Image.Image) -> Image.Image: - """Macht rein schwarze Außenpixel außerhalb der Button-Zierspitzen transparent.""" + """ + 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] rgba = pil_img.convert("RGBA") - px = rgba.load() w, h = rgba.size + tl = rgba.getpixel((0, 0)) - if px[0, 0][3] > 240 and max(px[0, 0][:3]) < 14: - visited = bytearray(w * h) - stack = [ - (0, 0), (w - 1, 0), (0, h - 1), (w - 1, h - 1), - (w // 2, 0), (w // 2, h - 1), (0, h // 2), (w - 1, h // 2), - ] - while stack: - x, y = stack.pop() - idx = y * w + x - if visited[idx]: - continue - visited[idx] = 1 - r, g, b, a = px[x, y] - mx = max(r, g, b) - if mx < 18: - new_a = 0 if mx < 8 else int((mx - 8) * 25.5) - px[x, y] = (r, g, b, min(a, new_a)) - if x > 0: - stack.append((x - 1, y)) - if x + 1 < w: - stack.append((x + 1, y)) - if y > 0: - stack.append((x, y - 1)) - if y + 1 < h: - stack.append((x, y + 1)) + # 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)) _ALPHA_CORNER_CACHE[key] = rgba return rgba @@ -311,6 +304,20 @@ class ImageButton(tk.Label): if base_pil is None: return None + cache_key = ( + id(base_pil), + self._width, + self._height, + self._text, + self._font_px, + text_color, + dim_disabled, + brighten_active, + ) + cached = _BTN_PHOTO_CACHE.get(cache_key) + if cached is not None: + return cached + bg, cap_w = _scale_button_3slice(base_pil, self._width, self._height) if dim_disabled: @@ -327,7 +334,6 @@ class ImageButton(tk.Label): if self._text: draw = ImageDraw.Draw(bg) - # Verfügbare Innenbreite strikt zwischen linker und rechter Zierkappe! side_inset = cap_w + 5 max_txt_w = max(20, self._width - 2 * side_inset) f_px = self._font_px @@ -372,7 +378,90 @@ class ImageButton(tk.Label): draw.text((cur_x, cur_y), ch, font=pil_font, fill=text_color) cur_x += draw.textlength(ch, font=pil_font) + FONT_LETTER_SPACING_PX - return ImageTk.PhotoImage(bg) + photo = ImageTk.PhotoImage(bg) + if len(_BTN_PHOTO_CACHE) > 400: + _BTN_PHOTO_CACHE.clear() + _BTN_PHOTO_CACHE[cache_key] = photo + return photo + + 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 + self._photo_active = None + + def _ensure_normal(self) -> ImageTk.PhotoImage | None: + if self._photo_normal is None: + c_norm, _, _, _ = self._palette() + self._photo_normal = self._compose_button_photo(self._pil_normal, c_norm) + return self._photo_normal + + def _ensure_hover(self) -> ImageTk.PhotoImage | None: + if self._photo_hover is None: + _, c_hov, _, _ = self._palette() + self._photo_hover = self._compose_button_photo(self._pil_hover, c_hov) + return self._photo_hover + + def _ensure_active(self) -> ImageTk.PhotoImage | None: + if self._photo_active is None: + _, _, c_act, _ = self._palette() + self._photo_active = self._compose_button_photo(self._pil_hover, c_act, brighten_active=True) + return self._photo_active + + def _ensure_disabled(self) -> ImageTk.PhotoImage | None: + if self._photo_disabled is None: + _, _, _, c_dis = self._palette() + self._photo_disabled = self._compose_button_photo(self._pil_normal, c_dis, dim_disabled=True) + return self._photo_disabled + + def set_enabled(self, enabled: bool): + self._enabled = bool(enabled) + if not self._enabled: + self._hovered = False + ph = self._ensure_disabled() + self.configure(image=ph if ph else "", cursor="arrow") + else: + ph = self._ensure_hover() if self._hovered else self._ensure_normal() + self.configure(image=ph if ph else "", cursor="hand2") + + def _on_enter(self, _event): + if not self._enabled: + return + self._hovered = True + ph = self._ensure_hover() + if ph: + self.configure(image=ph) + + def _on_leave(self, _event): + self._hovered = False + if not self._enabled: + return + ph = self._ensure_normal() + if ph: + self.configure(image=ph) + + def _on_press(self, _event): + if not self._enabled: + return + ph = self._ensure_active() + if ph: + self.configure(image=ph) + + 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 + ph = self._ensure_hover() if inside else self._ensure_normal() + if ph: + self.configure(image=ph) + if inside: + if self._sound_mgr: + self._sound_mgr.play("click") + if self._user_cmd: + self._user_cmd() def _rebuild_state_photos(self): c_norm, c_hov, c_act, c_dis = self._palette() diff --git a/view/widgets/menu_body_canvas.py b/view/widgets/menu_body_canvas.py new file mode 100644 index 0000000..840fc73 --- /dev/null +++ b/view/widgets/menu_body_canvas.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- +# view/widgets/menu_body_canvas.py +from __future__ import annotations + +import tkinter as tk +from PIL import Image, ImageTk + +from resources.code_res.game_constants import BG_COLOR +from view.widgets.goth_dropdown import GothDropdown + + +class MenuBodyCanvas(tk.Canvas): + """ + Vollflächiges Menü-Canvas unterhalb der GothTopbar: + Dockt per pack() strikt UNTER der Topbar an (überdeckt sie niemals) und + holt sich seinen Hintergrund-Ausschnitt aus dem geteilten AssetManager-Cache. + """ + + def __init__(self, ctx, topbar_h: int = 0): + GothDropdown.close_any_open_popup() + super().__init__(ctx.root, bg=BG_COLOR, bd=0, highlightthickness=0) + self.ctx = ctx + self._last_key: tuple[int, int, int, int, int] = (0, 0, -1, 0, 0) + self._bg_photo: ImageTk.PhotoImage | None = None + + self.pack(fill="both", expand=True) + # Sofortiges Vorzeichnen mit bekannter Root-Größe -> 0 Frames Leerlauf! + rw = ctx.root.winfo_width() + rh = ctx.root.winfo_height() + top_h = max(84, int(rh * 0.135)) + if rw >= 200 and rh > top_h + 80: + self._bg_photo = ctx.assets.get_bg_patch_photo(rw, rh, 0, top_h, rw, rh - top_h) + if self._bg_photo is not None: + self._last_key = (rw, rh - top_h, top_h, rw, rh) + self.create_image(0, 0, image=self._bg_photo, anchor="nw", tags="menu_bg") + self.tag_lower("menu_bg") + + def sync_bg(self, w: int, h: int): + if w < 80 or h < 80: + return + rw = max(w, self.ctx.root.winfo_width()) + rh = max(h, self.ctx.root.winfo_height()) + oy = max(0, min(rh - h, self.winfo_rooty() - self.ctx.root.winfo_rooty())) + + key = (w, h, oy, rw, rh) + if key == self._last_key: + return + self._last_key = key + + if hasattr(self.ctx.assets, "get_bg_patch_photo"): + self._bg_photo = self.ctx.assets.get_bg_patch_photo(rw, rh, 0, oy, w, h) + else: + src = ( + self.ctx.assets.raw_bg_vertical + if (rh > rw 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 None: + return + full_img = src.resize((rw, rh), Image.Resampling.BILINEAR) + self._bg_photo = ImageTk.PhotoImage(full_img.crop((0, oy, min(rw, w), min(rh, oy + h)))) + + if self._bg_photo is None: + return + self.delete("menu_bg") + self.create_image(0, 0, image=self._bg_photo, anchor="nw", tags="menu_bg") + self.tag_lower("menu_bg") \ No newline at end of file diff --git a/view/widgets/resizing_bg.py b/view/widgets/resizing_bg.py index 90b60e1..c2ceebe 100644 --- a/view/widgets/resizing_bg.py +++ b/view/widgets/resizing_bg.py @@ -1,55 +1,123 @@ # -*- coding: utf-8 -*- # view/widgets/resizing_bg.py +from __future__ import annotations + import tkinter as tk from PIL import Image, ImageTk +from resources.code_res.game_constants import BG_COLOR + class ResizingBG(tk.Canvas): """ - Vollbild-Hintergrund-Canvas: - Wechselt je nach Seitenverhältnis automatisch zwischen background_horizontal.jpg (w >= h) - und background_vertical.jpg (h > w) und dient gleichzeitig als rahmenlose Zeichenfläche. + Persistentes Vollbild-Hintergrund-Canvas für das Hauptfenster: + - Bleibt über alle View-Wechsel hinweg bestehen (verhindert Schwarz-Flackern unter X11/Crostini & Windows). + - Nutzt den zentralen get_bg_patch_photo()-Cache aus AssetManager (kein doppeltes Vollbild-Skalieren). + - Zeichnet sofort im Konstruktor vor, falls das Elternfenster bereits eine Größe hat (0 Frames Leerlauf). """ - def __init__(self, parent, pil_horizontal, pil_vertical=None, **kwargs): - kwargs.setdefault("highlightthickness", 0) - kwargs.setdefault("bd", 0) - super().__init__(parent, **kwargs) - self.raw_horiz = pil_horizontal - self.raw_vert = pil_vertical or pil_horizontal - self._photo = None - self._resize_job = None - self._last_size = (0, 0) - self.bind("", self._on_resize, add="+") - def _pick_source_image(self, w: int, h: int): - if h > w and self.raw_vert is not None: - return self.raw_vert - return self.raw_horiz or self.raw_vert + def __init__(self, parent, assets): + super().__init__( + parent, + bg=BG_COLOR, + bd=0, + highlightthickness=0, + ) + self.assets = assets + self._bg_photo: ImageTk.PhotoImage | None = None + self._last_size: tuple[int, int] = (0, 0) + self._resize_job: str | None = None - def _on_resize(self, event): - if event.widget != self: + self.bind("", self._on_configure) + self.bind("", self._on_destroy) + + # Sofortiges Vorzeichnen mit bekannter Elternfenster-Größe (vermeidet schwarzen Erst-Frame) + try: + pw = parent.winfo_width() + ph = parent.winfo_height() + if pw >= 200 and ph >= 200: + self._apply_bg(pw, ph) + except Exception: + pass + + def _on_destroy(self, event=None): + if event is not None and event.widget is not self: return - w, h = max(1, event.width), max(1, event.height) - if (w, h) == self._last_size: - return - if self._resize_job: + if self._resize_job is not None: try: self.after_cancel(self._resize_job) except Exception: pass - if self._photo is None: - self._render(w, h) - else: - self._resize_job = self.after(45, lambda: self._render(w, h)) + self._resize_job = None - def _render(self, w: int, h: int): + def _on_configure(self, event): + if event.widget is not self: + return + w, h = max(1, event.width), max(1, event.height) + if w < 100 or h < 100 or (w, h) == self._last_size: + return + + if self._resize_job is not None: + try: + self.after_cancel(self._resize_job) + except Exception: + pass + self._resize_job = None + + # Beim allerersten echten Layout sofort zeichnen, beim Ziehen am Fensterrand sanft entprellen (35 ms) + if self._last_size == (0, 0): + self._apply_bg(w, h) + else: + self._resize_job = self.after(35, self._apply_bg, w, h) + + def _apply_bg(self, w: int, h: int): self._resize_job = None - src = self._pick_source_image(w, h) - if not self.winfo_exists() or src is None: + if not self.winfo_exists() or (w, h) == self._last_size: return self._last_size = (w, h) - resized = src.resize((w, h), Image.Resampling.LANCZOS) - self._photo = ImageTk.PhotoImage(resized) - self.delete("bg_img") - self.create_image(0, 0, image=self._photo, anchor="nw", tags="bg_img") - self.tag_lower("bg_img") \ No newline at end of file + + photo: ImageTk.PhotoImage | None = None + if hasattr(self.assets, "get_bg_patch_photo"): + photo = self.assets.get_bg_patch_photo(w, h, 0, 0, w, h) + else: + src = ( + self.assets.raw_bg_vertical + if (h > w and getattr(self.assets, "raw_bg_vertical", None) is not None) + else (getattr(self.assets, "raw_bg_horizontal", None) or getattr(self.assets, "raw_bg", None)) + ) + if src is not None: + rgb_src = src.convert("RGB") if src.mode != "RGB" else src + photo = ImageTk.PhotoImage(rgb_src.resize((w, h), Image.Resampling.BILINEAR)) + + if photo is None: + return + + self._bg_photo = photo + existing = self.find_withtag("root_bg_img") + if existing: + self.itemconfigure(existing[0], image=self._bg_photo) + else: + self.create_image(0, 0, image=self._bg_photo, anchor="nw", tags=("root_bg_img",)) + self.tag_lower("root_bg_img") + + def clear_foreground(self): + """ + Räumt alle Vordergrund-Elemente UND fremde Event-Bindings (z. B. aus LoginView / MainMenuView) + restlos ab, lässt aber das gerenderte Hintergrundbild ('root_bg_img') stehen. + """ + # 1. Alte -Handler vorheriger Views entfernen und nur eigenen BG-Handler wiederherstellen + self.unbind("") + self.bind("", self._on_configure) + + # 2. Aufgesetzte Sub-Widgets (Buttons, Dropdowns, Entries) zerstören + for sub in list(self.winfo_children()): + try: + sub.destroy() + except Exception: + pass + + # 3. Alle gezeichneten Canvas-Items löschen AUSSER dem Hintergrundbild 'root_bg_img' + keep_ids = set(self.find_withtag("root_bg_img")) + for item_id in self.find_all(): + if item_id not in keep_ids: + self.delete(item_id) \ No newline at end of file