diff --git a/games/blackjack/views/__pycache__/round_result_dialog.cpython-311.pyc b/games/blackjack/views/__pycache__/round_result_dialog.cpython-311.pyc index 1b75ec4..9fd2ff7 100644 Binary files a/games/blackjack/views/__pycache__/round_result_dialog.cpython-311.pyc and b/games/blackjack/views/__pycache__/round_result_dialog.cpython-311.pyc differ diff --git a/games/blackjack/views/round_result_dialog.py b/games/blackjack/views/round_result_dialog.py index c8e47ae..802fd4c 100644 --- a/games/blackjack/views/round_result_dialog.py +++ b/games/blackjack/views/round_result_dialog.py @@ -14,23 +14,22 @@ from resources.code_res.game_constants import ( FONT_COLOR_STATUS_WIN, FONT_COLOR_TITLE_MAIN, FONT_SIZE_BODY, - FONT_SIZE_HEADING, FONT_SIZE_SMALL_MIN, FONT_SIZE_TITLE_LG, - OUTCOME_GIF_SIZE, SUBTLE_BORDER, ) from resources.code_res.i18n import t +from view.widgets.goth_dropdown import GothDropdown from view.widgets.image_button import ImageButton +from view.widgets.modal_veil import ModalVeil SHOWDOWN_MINI_CARD_SIZE = (48, 70) class BlackjackResultDialog(tk.Canvas): """ - Rahmenloses Gothic-Showdown-Overlay für Blackjack: - Hintergrund background_vertical.jpg + box_big.png, Gewinner-Sitze in box_gold_smal.png, - übrige Sitze in box_small_purple.png und kompakte Kartenfächer für 768p-Bildschirme. + Rahmenloses Gothic-Showdown-Overlay für Blackjack (ohne eingebettetes GIF), + immer über allen UI-Leisten platziert und mit abgedunkeltem, gesperrtem Tisch. """ def __init__( @@ -42,30 +41,31 @@ class BlackjackResultDialog(tk.Canvas): on_next_round, on_back_to_menu, ): + GothDropdown.close_any_open_popup() + top_root = parent.winfo_toplevel() + hands_list = result_data.get("showdown_hands", []) cols = min(3, max(1, len(hands_list))) rows = (len(hands_list) + 2) // 3 if hands_list else 0 - has_gif = result_data.get("player_won") is not None extra_lines = len(result_data.get("other_gains", [])) dlg_w = max(560, min(830, cols * 250 + 64)) dlg_h = ( - (116 if has_gif else 54) + 58 + (48 if result_data.get("reason_text") else 8) + (rows * 140 + 28 if rows else 0) + 92 + min(2, extra_lines) * 20 + (24 if result_data.get("new_level_title") else 0) + 62 ) - # Sicherstellen, dass das Dialogfenster auch auf 768p-Displays komplett sichtbar bleibt try: - max_h = max(460, parent.winfo_toplevel().winfo_height() - 74) + max_h = max(420, top_root.winfo_height() - 60) dlg_h = min(dlg_h, max_h) except Exception: pass super().__init__( - parent, + top_root, width=dlg_w, height=dlg_h, bg=BG_COLOR, @@ -80,20 +80,17 @@ class BlackjackResultDialog(tk.Canvas): self._dlg_w = dlg_w self._dlg_h = dlg_h - self._gif_job: str | None = None - self._gif_item: int | None = None self._photo_refs: list = [] self.place(relx=0.5, rely=0.5, anchor="center") - self.tk.call("raise", self._w) self._build_scene() + self._veil = ModalVeil(top_root, assets, modal_widget=self) def _build_scene(self): w, h = self._dlg_w, self._dlg_h cx = w // 2 self._photo_refs.clear() - # 1. Hintergrund + äußerer Zierrahmen box_big.png bg_src = self.assets.raw_bg_vertical or self.assets.raw_bg_horizontal or self.assets.raw_bg if bg_src is not None: bg_ph = ImageTk.PhotoImage(bg_src.resize((w, h), Image.Resampling.LANCZOS)) @@ -105,18 +102,9 @@ class BlackjackResultDialog(tk.Canvas): self._photo_refs.append(outer_box) self.create_image(cx, h // 2, image=outer_box, anchor="center") - cur_y = 20 + cur_y = 26 - # 2. Win/Lose GIF + Headline p_won = self.data.get("player_won") - gif_key = "win_gif" if p_won is True else ("lose_gif" if p_won is False else "") - frames = self.assets.get_gif_frames(gif_key, size=(145, 80)) if gif_key else [] - if frames: - self._gif_item = self.create_image(cx, cur_y + 40, image=frames[0], anchor="center") - cur_y += 84 - if len(frames) > 1: - self._animate_gif(frames, 0) - hl_col = ( FONT_COLOR_TITLE_MAIN if p_won is True @@ -127,9 +115,8 @@ class BlackjackResultDialog(tk.Canvas): ) self._photo_refs.append(hl_ph) self.create_image(cx, cur_y + hl_ph.height() // 2, image=hl_ph, anchor="center") - cur_y += hl_ph.height() + 6 + cur_y += hl_ph.height() + 8 - # 3. Begründung im schmalen Gold-Doppelrahmen reason_txt = self.data.get("reason_text", "") if reason_txt: r_ph = self.assets.get_goth_text_photo( @@ -145,7 +132,6 @@ class BlackjackResultDialog(tk.Canvas): self.create_image(cx, rb_cy, image=r_ph, anchor="center") cur_y += rb_h + 8 - # 4. Showdown-Karten aller Teilnehmer hands_list = self.data.get("showdown_hands", []) if hands_list: sec_ph = self.assets.get_goth_text_photo( @@ -192,7 +178,6 @@ class BlackjackResultDialog(tk.Canvas): self._photo_refs.append(o_ph) self.create_image(sx, sy - seat_h // 2 + 20, image=o_ph, anchor="center") - # Überlappender Mini-Kartenfächer c_imgs = entry.get("card_images", []) c_photos = [] for img_name in c_imgs: @@ -226,7 +211,6 @@ class BlackjackResultDialog(tk.Canvas): cur_y += rows * (seat_h + 6) + 6 - # 5. Gold- & XP-Abrechnung self.create_line(36, cur_y, w - 36, cur_y, fill=SUBTLE_BORDER, width=1) cur_y += 10 @@ -257,13 +241,13 @@ class BlackjackResultDialog(tk.Canvas): if self.data.get("new_level_title"): xp_line = f"{xp_line} • {self.data['new_level_title']}" xp_ph = self.assets.get_goth_text_photo( - xp_line, FONT_SIZE_BODY, FONT_COLOR_TITLE_MAIN if self.data.get("new_level_title") else FONT_COLOR_HEADING_SUB, + xp_line, FONT_SIZE_BODY, + FONT_COLOR_TITLE_MAIN if self.data.get("new_level_title") else FONT_COLOR_HEADING_SUB, max_width=w - 72, ) self._photo_refs.append(xp_ph) self.create_image(cx, cur_y + xp_ph.height() // 2, image=xp_ph, anchor="center") - # 6. Untere Buttons btn_norm = self.assets.raw_btn_default btn_purp = self.assets.raw_btn_purple btn_fire = self.assets.raw_btn_fire or btn_purp @@ -296,19 +280,8 @@ class BlackjackResultDialog(tk.Canvas): ) self.create_window(cx, btn_y, window=b_menu, anchor="center") - 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 close_dialog(self): - if self._gif_job: - try: - self.after_cancel(self._gif_job) - except Exception: - pass - self._gif_job = None + self._veil.release() self._photo_refs.clear() if self.winfo_exists(): self.destroy() diff --git a/games/poker/views/__pycache__/poker_result_dialog.cpython-311.pyc b/games/poker/views/__pycache__/poker_result_dialog.cpython-311.pyc index 23ccc3a..3039ea1 100644 Binary files a/games/poker/views/__pycache__/poker_result_dialog.cpython-311.pyc and b/games/poker/views/__pycache__/poker_result_dialog.cpython-311.pyc differ diff --git a/games/poker/views/poker_result_dialog.py b/games/poker/views/poker_result_dialog.py index d3755df..1d5dce4 100644 --- a/games/poker/views/poker_result_dialog.py +++ b/games/poker/views/poker_result_dialog.py @@ -1,21 +1,34 @@ # -*- coding: utf-8 -*- # games/poker/views/poker_result_dialog.py +from __future__ import annotations + import tkinter as tk from models.card import Card from resources.code_res.game_constants import ( - ACCENT_GOLD, ACCENT_GOTH, CELL_BG, ERROR_FG, - FG_COLOR, MODAL_BG, MUTED_FG, SUBTLE_BORDER + ACCENT_GOLD, + ACCENT_GOTH, + CELL_BG, + ERROR_FG, + FG_COLOR, + MODAL_BG, + MUTED_FG, + SUBTLE_BORDER, ) from resources.code_res.i18n import t +from view.widgets.goth_dropdown import GothDropdown from view.widgets.image_button import ImageButton +from view.widgets.modal_veil import ModalVeil -POPUP_GIF_SIZE = (145, 80) POPUP_HOLE_CARD_SIZE = (48, 70) POPUP_BOARD_CARD_SIZE = (44, 64) class PokerResultDialog(tk.Frame): - """Ergebnis-Overlay im einheitlichen BlackjackResultDialog-Stil inkl. Kartenbild-Showdown.""" + """ + Ergebnis-Overlay für Texas Hold'em (ohne eingebettetes GIF), + immer über allen UI-Leisten platziert und mit abgedunkeltem, gesperrtem Tisch. + """ + def __init__( self, parent, @@ -25,45 +38,50 @@ class PokerResultDialog(tk.Frame): on_next_round, on_back_to_menu, ): + GothDropdown.close_any_open_popup() + top_root = parent.winfo_toplevel() + super().__init__( - parent, bg=MODAL_BG, padx=26, pady=18, - highlightthickness=2, highlightbackground=ACCENT_GOTH + top_root, + bg=MODAL_BG, + padx=26, + pady=18, + highlightthickness=2, + highlightbackground=ACCENT_GOTH, ) self.assets = assets self.sounds = sounds self.data = result_data self.on_next_round = on_next_round self.on_back_to_menu = on_back_to_menu - self._gif_job = None self._card_photos = [] self.place(relx=0.5, rely=0.5, anchor="center") - self.lift() self._build() + self._veil = ModalVeil(top_root, assets, modal_widget=self) def _build(self): - self.gif_lbl = tk.Label(self, bg=MODAL_BG, bd=0) - self.gif_lbl.pack(pady=(0, 4)) - p_won = self.data.get("player_won") - if p_won is True: - self._start_gif("win_gif") - elif p_won is False: - self._start_gif("lose_gif") - headline_color = ACCENT_GOLD if p_won else ( MUTED_FG if p_won is None else ERROR_FG ) tk.Label( - self, text=self.data["headline"], - font=("Georgia", 16, "bold"), fg=headline_color, bg=MODAL_BG, - wraplength=680, justify="center" + self, + text=self.data["headline"], + font=("Georgia", 16, "bold"), + fg=headline_color, + bg=MODAL_BG, + wraplength=680, + justify="center", ).pack(pady=(2, 10)) - # --- Karten-Aufdeckung: Gemeinschaftskarten + alle Sitze mit Kartenbildern --- reveal_box = tk.Frame( - self, bg=CELL_BG, padx=12, pady=8, - highlightthickness=1, highlightbackground=SUBTLE_BORDER + self, + bg=CELL_BG, + padx=12, + pady=8, + highlightthickness=1, + highlightbackground=SUBTLE_BORDER, ) reveal_box.pack(fill="x", pady=(0, 10)) @@ -72,8 +90,11 @@ class PokerResultDialog(tk.Frame): b_row = tk.Frame(reveal_box, bg=CELL_BG) b_row.pack(pady=(0, 6)) tk.Label( - b_row, text=f"{t('pk_board_title')}:", - font=("Georgia", 9, "bold"), fg=MUTED_FG, bg=CELL_BG + b_row, + text=f"{t('pk_board_title')}:", + font=("Georgia", 9, "bold"), + fg=MUTED_FG, + bg=CELL_BG, ).pack(side="left", padx=(0, 8)) for s_suit, s_rank in board_raw: @@ -94,15 +115,22 @@ class PokerResultDialog(tk.Frame): border_c = ACCENT_GOLD if is_win else (SUBTLE_BORDER if not folded else "#3a252a") s_card = tk.Frame( - seats_row, bg="#191521", padx=8, pady=5, - highlightthickness=2 if is_win else 1, highlightbackground=border_c + seats_row, + bg="#191521", + padx=8, + pady=5, + highlightthickness=2 if is_win else 1, + highlightbackground=border_c, ) s_card.grid(row=idx // 6, column=idx % 6, padx=4, pady=2, sticky="nsew") name_col = ACCENT_GOLD if is_win else (MUTED_FG if folded else ACCENT_GOTH) tk.Label( - s_card, text=entry["name"], - font=("Georgia", 9, "bold"), fg=name_col, bg="#191521" + s_card, + text=entry["name"], + font=("Georgia", 9, "bold"), + fg=name_col, + bg="#191521", ).pack() c_frame = tk.Frame(s_card, bg="#191521", height=POPUP_HOLE_CARD_SIZE[1] + 2) @@ -116,15 +144,22 @@ class PokerResultDialog(tk.Frame): combo_col = "#7be08a" if is_win else (ERROR_FG if folded else FG_COLOR) tk.Label( - s_card, text=entry["combo_text"], - font=("Helvetica", 8, "bold"), fg=combo_col, bg="#191521", - wraplength=112, justify="center" + s_card, + text=entry["combo_text"], + font=("Helvetica", 8, "bold"), + fg=combo_col, + bg="#191521", + wraplength=112, + justify="center", ).pack() - # --- Gewinn / Verlust & XP Box (identisch zu BlackjackResultDialog) --- info_box = tk.Frame( - self, bg=CELL_BG, padx=20, pady=10, - highlightthickness=1, highlightbackground=SUBTLE_BORDER + self, + bg=CELL_BG, + padx=20, + pady=10, + highlightthickness=1, + highlightbackground=SUBTLE_BORDER, ) info_box.pack(fill="x", pady=(0, 12)) @@ -144,54 +179,57 @@ class PokerResultDialog(tk.Frame): tk.Frame(info_box, bg=SUBTLE_BORDER, height=1).pack(fill="x", pady=8) tk.Label( - info_box, text=t("bj_popup_xp_earned", self.data["xp_gained"]), - font=("Helvetica", 11, "bold"), fg=ACCENT_GOTH, bg=CELL_BG, + info_box, + text=t("bj_popup_xp_earned", self.data["xp_gained"]), + font=("Helvetica", 11, "bold"), + fg=ACCENT_GOTH, + bg=CELL_BG, ).pack(pady=1) if self.data.get("new_level_title"): tk.Label( - info_box, text=self.data["new_level_title"], - font=("Georgia", 11, "bold"), fg=ACCENT_GOLD, bg=CELL_BG, + info_box, + text=self.data["new_level_title"], + font=("Georgia", 11, "bold"), + fg=ACCENT_GOLD, + bg=CELL_BG, ).pack(pady=(3, 0)) - # --- Buttons --- btn_row = tk.Frame(self, bg=MODAL_BG) btn_row.pack(fill="x", pady=(4, 0)) + btn_norm = self.assets.raw_btn_default + btn_purp = self.assets.raw_btn_purple + btn_fire = self.assets.raw_btn_fire or btn_purp + if self.data.get("can_continue", True): ImageButton( - btn_row, t("bj_popup_next_round_btn"), - self.assets.raw_btn, self.assets.raw_btn_active, - self._handle_next, sound_mgr=self.sounds, width=200, height=40, font=("Helvetica", 10, "bold") + btn_row, + t("bj_popup_next_round_btn"), + btn_fire, + btn_fire, + self._handle_next, + sound_mgr=self.sounds, + width=200, + height=38, + style="fire", ).pack(side="left", padx=(0, 10)) if self.data.get("can_leave_menu", True): ImageButton( - btn_row, t("bj_popup_to_menu_btn"), - self.assets.raw_sel, self.assets.raw_sel_active, - self._handle_menu, sound_mgr=self.sounds, width=170, height=40, font=("Helvetica", 10, "bold") + btn_row, + t("bj_popup_to_menu_btn"), + btn_norm, + btn_purp, + self._handle_menu, + sound_mgr=self.sounds, + width=170, + height=38, + style="amethyst", ).pack(side="right") - def _start_gif(self, key: str): - frames = self.assets.get_gif_frames(key, size=POPUP_GIF_SIZE) - if not frames: - return - - def _step(idx=0): - if not self.gif_lbl.winfo_exists(): - return - self.gif_lbl.configure(image=frames[idx]) - self._gif_job = self.after(90, _step, (idx + 1) % len(frames)) - - _step(0) - def close_dialog(self): - if self._gif_job: - try: - self.after_cancel(self._gif_job) - except Exception: - pass - self._gif_job = None + self._veil.release() if self.winfo_exists(): self.destroy() diff --git a/games/solitaire/base/card_hover_zoom.py b/games/solitaire/base/card_hover_zoom.py new file mode 100644 index 0000000..a780cd0 --- /dev/null +++ b/games/solitaire/base/card_hover_zoom.py @@ -0,0 +1,266 @@ +# -*- coding: utf-8 -*- +# games/solitaire/base/card_hover_zoom.py +from __future__ import annotations + +import tkinter as tk +from typing import Callable + +from games.solitaire.base.solitaire_card import SolitaireCard +from resources.code_res.game_constants import ACCENT_GOLD, BORDER_COLOR + + +class CardHoverZoom: + """ + Subtile Karten-Hervorhebung im Stil von Microsoft Solitaire: + Hebt die Karte unter dem Mauszeiger leicht vergrößert und nach oben versetzt hervor, + behält aber strikt die Stapel-Reihenfolge (Z-Order) bei, sodass alle Karten, die in + einer Kaskade auf ihr liegen, weiterhin vollständig sichtbar bleiben. + """ + + ZOOM_FACTOR = 1.12 # Dezente Verbreitung/Vergrößerung unter den Folgekarten + PEEK_UP_PX = 8 # Leichtes Anheben nach oben, damit Wert & Symbol frei herausschauen + HOVER_DELAY_MS = 45 + TAG = "sol_hover_zoom" + + def __init__( + self, + root: tk.Misc, + canvas: tk.Canvas, + assets, + probe_fn: Callable[[int, int], dict | tuple | None], + can_show_fn: Callable[[], bool] | None = None, + ): + self._root = root + self._canvas = canvas + self._assets = assets + self._probe_fn = probe_fn + self._can_show_fn = can_show_fn + + self._after_job: str | None = None + self._active_target_id: tuple | None = None + self._pending_info: dict | None = None + self._last_pointer_xy: tuple[int, int] | None = None + self._zoom_photo_ref = None + + self._canvas.bind("", self._on_motion, add="+") + self._canvas.bind("", self._on_leave, add="+") + self._canvas.bind("", self._on_press_clear, add="+") + self._canvas.bind("", self._on_press_clear, add="+") + + @staticmethod + def _normalize_probe(raw: dict | tuple | None) -> dict | None: + if raw is None: + return None + if isinstance(raw, dict): + return raw + if isinstance(raw, tuple) and len(raw) >= 4: + card, cx, cy, base_sz = raw[:4] + under_tag = raw[4] if len(raw) >= 5 else None + return { + "card": card, + "x": cx, + "y": cy, + "size": base_sz, + "under_tag": under_tag, + } + return None + + def cancel(self): + """Räumt Timer und aktive Hervorhebung restlos ab.""" + self._cancel_timer() + self._clear_drawn() + self._active_target_id = None + self._pending_info = None + + def refresh_after_redraw(self): + """Stellt nach einem Hintergrund-Redraw (z. B. Uhr-Tick) die Hervorhebung sauber wieder her.""" + if self._active_target_id is None or self._last_pointer_xy is None: + return + if self._can_show_fn is not None and not self._can_show_fn(): + self.cancel() + return + px, py = self._last_pointer_xy + info = self._normalize_probe(self._probe_fn(px, py)) + if info is None: + self.cancel() + return + card: SolitaireCard = info["card"] + target_id = ( + card.suit, + card.rank, + card.deck_id, + info["x"], + info["y"], + info.get("under_tag"), + ) + if target_id == self._active_target_id: + self._render_zoom(info) + else: + self.cancel() + + def _cancel_timer(self): + if self._after_job is not None: + try: + self._root.after_cancel(self._after_job) + except Exception: + pass + self._after_job = None + + def _clear_drawn(self): + try: + if self._canvas.winfo_exists(): + self._canvas.delete(self.TAG) + except Exception: + pass + self._zoom_photo_ref = None + + def _on_leave(self, _event=None): + self._last_pointer_xy = None + self.cancel() + + def _on_press_clear(self, _event=None): + self.cancel() + + def _on_motion(self, event): + # Während Drag & Drop niemals einblenden + if event.state & 0x0100: + self.cancel() + return + + self._last_pointer_xy = (event.x, event.y) + + if self._can_show_fn is not None and not self._can_show_fn(): + self.cancel() + return + + info = self._normalize_probe(self._probe_fn(event.x, event.y)) + if info is None: + self.cancel() + return + + card: SolitaireCard = info["card"] + if not card.face_up: + self.cancel() + return + + target_id = ( + card.suit, + card.rank, + card.deck_id, + info["x"], + info["y"], + info.get("under_tag"), + ) + if target_id == self._active_target_id: + return + + self._cancel_timer() + self._clear_drawn() + self._active_target_id = None + self._pending_info = info + try: + self._after_job = self._root.after(self.HOVER_DELAY_MS, self._show_pending) + except Exception: + self._after_job = None + + def _show_pending(self): + self._after_job = None + if self._pending_info is None: + return + if self._can_show_fn is not None and not self._can_show_fn(): + self._pending_info = None + return + if not self._canvas.winfo_exists(): + return + + info = self._pending_info + card: SolitaireCard = info["card"] + self._active_target_id = ( + card.suit, + card.rank, + card.deck_id, + info["x"], + info["y"], + info.get("under_tag"), + ) + self._render_zoom(info) + + def _render_zoom(self, info: dict): + self._clear_drawn() + card: SolitaireCard = info["card"] + card_x: int = info["x"] + card_y: int = info["y"] + bw, bh = info["size"] + under_tag: str | None = info.get("under_tag") + + if bw < 24 or bh < 32: + return + + zw = max(bw + 8, int(round(bw * self.ZOOM_FACTOR))) + zh = max(bh + 12, int(round(bh * self.ZOOM_FACTOR))) + + cw = max(1, self._canvas.winfo_width()) + ch = max(1, self._canvas.winfo_height()) + + # Horizontal mittig auf der Spalte, vertikal leicht nach oben gelupft ("Peek"), + # damit Rang & Farbe über den aufliegenden Folgekarten klar hervortreten + zx = card_x - (zw - bw) // 2 + if under_tag: + zy = card_y - self.PEEK_UP_PX - (zh - bh) // 3 + else: + zy = card_y - (zh - bh) // 2 + + pad = 6 + zx = max(pad, min(max(pad, cw - zw - pad), zx)) + zy = max(pad, min(max(pad, ch - zh - pad), zy)) + + photo = self._assets.get_card_photo(card.filename, size=(zw, zh)) + if photo is None: + return + self._zoom_photo_ref = photo + + # 1. Dezenter dunkler Schlagschatten + self._canvas.create_rectangle( + zx + 4, + zy + 5, + zx + zw + 4, + zy + zh + 5, + fill="#07050c", + outline="", + tags=(self.TAG,), + ) + # 2. Leicht vergrößerte Karte + self._canvas.create_image( + zx, + zy, + image=photo, + anchor="nw", + tags=(self.TAG,), + ) + # 3. Goldener Hervorhebungs-Rahmen + self._canvas.create_rectangle( + zx - 2, + zy - 2, + zx + zw + 2, + zy + zh + 2, + outline=ACCENT_GOLD, + width=2, + tags=(self.TAG,), + ) + self._canvas.create_rectangle( + zx - 3, + zy - 3, + zx + zw + 3, + zy + zh + 3, + outline=BORDER_COLOR, + width=1, + tags=(self.TAG,), + ) + + # Entscheidend: Liegen in der Kaskade weitere Karten auf dieser Karte, + # sortieren wir die Hervorhebung direkt UNTER die nächste Karte ein! + if under_tag and self._canvas.find_withtag(under_tag): + try: + self._canvas.tag_lower(self.TAG, under_tag) + except tk.TclError: + pass \ No newline at end of file diff --git a/games/solitaire/base/solitaire_modal_dialog.py b/games/solitaire/base/solitaire_modal_dialog.py index d7d8a99..91ed8a0 100644 --- a/games/solitaire/base/solitaire_modal_dialog.py +++ b/games/solitaire/base/solitaire_modal_dialog.py @@ -15,12 +15,13 @@ from resources.code_res.game_constants import ( ) from view.widgets.goth_dropdown import GothDropdown from view.widgets.image_button import ImageButton +from view.widgets.modal_veil import ModalVeil 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. + Rahmenloses Gothic-Modal (ohne eingebettetes GIF), das über allen UI-Elementen + schwebt, das Spielfeld dahinter abdunkelt und alle übrigen Buttons sperrt. """ def __init__( @@ -30,12 +31,12 @@ class SolitaireModalDialog(tk.Canvas): body_txt: str, buttons: list[tuple[str, str, object, bool] | tuple[str, str, object]], is_danger: bool = False, - gif_key: str = "", + gif_key: str = "", # abwärtskompatibel ignoriert (Animation läuft vorab) ): GothDropdown.close_any_open_popup() - frames = ctx.assets.get_gif_frames(gif_key, size=(150, 84)) if gif_key else [] + _ = gif_key dlg_w = 590 if len(buttons) >= 3 else 500 - dlg_h = 355 if frames else 268 + dlg_h = 268 super().__init__( ctx.root, @@ -49,28 +50,10 @@ class SolitaireModalDialog(tk.Canvas): 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)) + self.place(relx=0.5, rely=0.5, anchor="center") + self._build_scene(title_txt, body_txt, buttons, is_danger) + self._veil = ModalVeil(ctx.root, ctx.assets, modal_widget=self) def _build_scene( self, @@ -78,7 +61,6 @@ class SolitaireModalDialog(tk.Canvas): body_txt: str, buttons: list, is_danger: bool, - frames: list, ): w, h = self._dlg_w, self._dlg_h assets = self.ctx.assets @@ -94,15 +76,7 @@ class SolitaireModalDialog(tk.Canvas): 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 - + 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) diff --git a/games/solitaire/base/solitaire_tap_prefs.py b/games/solitaire/base/solitaire_tap_prefs.py new file mode 100644 index 0000000..dd81df6 --- /dev/null +++ b/games/solitaire/base/solitaire_tap_prefs.py @@ -0,0 +1,75 @@ +# -*- coding: utf-8 -*- +# games/solitaire/base/solitaire_tap_prefs.py +from __future__ import annotations + +import sqlite3 + +from models.database import Database + +TAP_TO_MOVE_SETTING_KEY = "sol_single_tap_to_move" +SINGLE_TAP_MAX_HOLD_SEC = 0.28 + +_single_tap_cache: bool | None = None + + +def _get_user_db_path() -> str: + for attr in ("USER_DB_PATH", "DB_PATH", "_user_db_path", "db_path"): + val = getattr(Database, attr, None) + if isinstance(val, str) and val.strip(): + return val + return "user_data.db" + + +def _load_persisted_flag(default: bool = False) -> bool: + try: + with sqlite3.connect(_get_user_db_path()) as conn: + conn.execute( + "CREATE TABLE IF NOT EXISTS app_settings (" + "key TEXT PRIMARY KEY, " + "val TEXT NOT NULL" + ")" + ) + row = conn.execute( + "SELECT val FROM app_settings WHERE key = ?", + (TAP_TO_MOVE_SETTING_KEY,), + ).fetchone() + if row is not None: + return str(row[0]).strip().lower() in ("1", "true", "yes", "on") + except Exception: + pass + return default + + +def _save_persisted_flag(enabled: bool) -> None: + try: + with sqlite3.connect(_get_user_db_path()) as conn: + conn.execute( + "CREATE TABLE IF NOT EXISTS app_settings (" + "key TEXT PRIMARY KEY, " + "val TEXT NOT NULL" + ")" + ) + conn.execute( + "INSERT OR REPLACE INTO app_settings (key, val) VALUES (?, ?)", + (TAP_TO_MOVE_SETTING_KEY, "1" if enabled else "0"), + ) + conn.commit() + except Exception: + pass + + +def is_single_tap_to_move_enabled() -> bool: + """Gibt zurück, ob 'Einfacher Klick zum Schieben' aktiv ist (mit In-Memory-Cache).""" + global _single_tap_cache + if _single_tap_cache is None: + _single_tap_cache = _load_persisted_flag(default=False) + return _single_tap_cache + + +def set_single_tap_to_move_enabled(enabled: bool, persist: bool = True) -> None: + """Aktiviert/deaktiviert 'Einfacher Klick zum Schieben' und speichert es optional in user_data.db.""" + global _single_tap_cache + state = bool(enabled) + _single_tap_cache = state + if persist: + _save_persisted_flag(state) \ No newline at end of file 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 070824f..9a63c58 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_table_view.py b/games/solitaire/freecell/views/freecell_table_view.py index f770175..d6f613f 100644 --- a/games/solitaire/freecell/views/freecell_table_view.py +++ b/games/solitaire/freecell/views/freecell_table_view.py @@ -6,10 +6,14 @@ import time import tkinter as tk from games.solitaire.base.card_animator import CardFlightAnimator +from games.solitaire.base.card_hover_zoom import CardHoverZoom 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_tap_prefs import ( + SINGLE_TAP_MAX_HOLD_SEC, + is_single_tap_to_move_enabled, +) from games.solitaire.base.solitaire_theme import SolitaireTableBgRenderer from games.solitaire.freecell.models.freecell_engine import FreeCellEngine from models.database import Database @@ -17,7 +21,6 @@ from models.progression import Progression from resources.code_res.game_constants import ( ACCENT_GOLD, ACCENT_GOTH, - BG_COLOR, BORDER_COLOR, CELL_BG, FONT_COLOR_TITLE_MAIN, @@ -34,6 +37,7 @@ from resources.code_res.game_constants import ( TABLE_BG, ) from resources.code_res.i18n import t +from view.widgets.endgame_fx_overlay import EndgameFxOverlay from view.widgets.image_button import ImageButton GAME_FOLDER_ID = "solitaire/freecell" @@ -87,6 +91,8 @@ class FreeCellTableView: self._bind_ids: list[tuple[str, str]] = [] self._auto_running = False self.animator: CardFlightAnimator | None = None + self.hover_zoom: CardHoverZoom | None = None + self._fx_overlay: EndgameFxOverlay | None = None self._bg_renderer = SolitaireTableBgRenderer(self.ctx.assets.res) self._frame_bot_pad: int = 18 self._canvas_ui_refs: list = [] @@ -120,6 +126,15 @@ class FreeCellTableView: d_mult = SOLITAIRE_DIFFICULTIES.get(self.difficulty, SOLITAIRE_DIFFICULTIES[1])["xp_mult"] return self.cfg["xp_mult"] * d_mult + def _is_ui_locked(self) -> bool: + return ( + self.engine.won + or self._game_concluded + or self._auto_running + or (self._modal_overlay is not None) + or (self._fx_overlay is not None) + ) + def _canvas_alive(self) -> bool: if not self._alive: return False @@ -128,6 +143,74 @@ class FreeCellTableView: except Exception: return False + def _can_show_hover_zoom(self) -> bool: + if not self._canvas_alive(): + return False + if self._is_ui_locked() or self._dragging or self._press_info is not None: + return False + if not self._window_active: + return False + if self.animator is not None and self.animator.is_active: + return False + return True + + def _hover_card_probe(self, x: int, y: int) -> dict | None: + cw, ch = self.card_size + + for fc_i in range(4): + fx = self._fc_x[fc_i] + if fx <= x <= fx + cw and self._top_y <= y <= self._top_y + ch: + c = self.engine.freecells[fc_i] + if c is not None and c.face_up: + return { + "card": c, + "x": fx, + "y": self._top_y, + "size": self.card_size, + "under_tag": None, + } + return None + + for f_idx in range(4): + fx = self._found_x[f_idx] + if fx <= x <= fx + cw and self._top_y <= y <= self._top_y + ch: + pile = self.engine.foundations[f_idx] + if pile and pile[-1].face_up: + return { + "card": pile[-1], + "x": fx, + "y": self._top_y, + "size": self.card_size, + "under_tag": None, + } + return None + + for col_idx in range(8): + rects = self._tableau_card_rects[col_idx] + col_cards = self.engine.tableau[col_idx] + for c_idx in range(len(rects) - 1, -1, -1): + if c_idx >= len(col_cards): + continue + x1, y1, x2, y2 = rects[c_idx] + if x1 <= x <= x2 and y1 <= y <= y2: + card = col_cards[c_idx] + if not card.face_up: + return None + next_tag = ( + f"fc_tab_{col_idx}_{c_idx + 1}" + if (c_idx + 1) < len(col_cards) + else None + ) + return { + "card": card, + "x": x1, + "y": y1, + "size": self.card_size, + "under_tag": next_tag, + } + + return None + def _play_table_music(self): for method_name in ("play_ingame_music", "play_table_music"): fn = getattr(self.ctx.sounds, method_name, None) @@ -161,6 +244,11 @@ class FreeCellTableView: def _cleanup_timers(self): self._alive = False self.engine.pause_timer() + if self._fx_overlay is not None: + self._fx_overlay.cancel() + self._fx_overlay = None + if self.hover_zoom is not None: + self.hover_zoom.cancel() if self.animator is not None: self.animator.cancel() for job in ( @@ -207,7 +295,13 @@ class FreeCellTableView: except Exception: return - should_run = has_focus and (self._modal_overlay is None) and (not self.engine.won) + should_run = ( + has_focus + and (self._modal_overlay is None) + and (self._fx_overlay is None) + and (not self._game_concluded) + and (not self.engine.won) + ) prev_paused = self.engine.is_timer_paused self._window_active = has_focus @@ -220,7 +314,7 @@ class FreeCellTableView: if prev_paused != self.engine.is_timer_paused: self._update_hud_text() - if self.animator is None or not self.animator.is_active: + if (self.animator is None or not self.animator.is_active) and self._fx_overlay is None: self.redraw() def _build_ui(self): @@ -230,18 +324,14 @@ class FreeCellTableView: self.topbar = self.ctx.build_game_topbar( self.ctx.root, - t(GAME_TITLE_KEY), - on_game_menu=self._back_to_game_menu, - on_stats=self._open_stats, + stats_endpoint=GAME_FOLDER_ID, stats_enabled=True, - extra_right_text="", on_lang_refresh=self._refresh_lang, ) self.hud_var = tk.StringVar(value="") self.status_var = tk.StringVar(value="") - # 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)) @@ -275,13 +365,21 @@ class FreeCellTableView: btn_norm, btn_purp, self._on_new_or_forfeit_clicked, sound_mgr=self.ctx.sounds, width=104, height=32, style="amethyst", ) - self.bottom_bar.set_buttons([ - self.undo_btn, self.undo_all_btn, self.hint_btn, self.auto_btn, self.new_btn - ]) + self.bottom_bar.set_buttons( + [self.undo_btn, self.undo_all_btn, self.hint_btn, self.auto_btn], + overflow_buttons=[self.new_btn], + ) 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.hover_zoom = CardHoverZoom( + self.ctx.root, + self.canvas, + self.ctx.assets, + probe_fn=self._hover_card_probe, + can_show_fn=self._can_show_hover_zoom, + ) self.canvas.bind("", self._on_canvas_configure) self.canvas.bind("", self._on_canvas_destroy) @@ -301,6 +399,8 @@ class FreeCellTableView: self._update_hud_text() def _on_undo_shortcut(self, _event=None): + if self._fx_overlay is not None or self._game_concluded: + return "break" if self.engine.can_undo and not self._auto_running: if self._modal_overlay is not None: self._close_active_modal() @@ -309,6 +409,8 @@ class FreeCellTableView: return "break" def _on_undo_all_shortcut(self, _event=None): + if self._fx_overlay is not None or self._game_concluded: + return "break" if self.engine.can_undo_all and not self._auto_running: if self._modal_overlay is not None: self._close_active_modal() @@ -341,28 +443,8 @@ class FreeCellTableView: resume_state_json=state_json, ) - def _open_stats(self): - if self.animator: - self.animator.flush() - self.engine.pause_timer() - self._save_progress() - state_json = self.engine.to_json() - self._cleanup_timers() - SolitaireStatsView( - self.ctx, - game_folder=GAME_FOLDER_ID, - game_title_key=GAME_TITLE_KEY, - on_back=lambda: FreeCellTableView( - self.ctx, - variant_key=self.variant_key, - difficulty=self.difficulty, - on_back_to_menu=self.on_back_to_menu, - resume_state_json=state_json, - ), - ).show() - def _back_to_game_menu(self): - if self._auto_running: + if self._auto_running or self._fx_overlay is not None: return if self.animator: self.animator.flush() @@ -387,7 +469,12 @@ class FreeCellTableView: self._check_window_focus() self._update_hud_text() - if self.engine.has_timer_started and not self.engine.is_timer_paused and not self.engine.won: + if ( + self.engine.has_timer_started + and not self.engine.is_timer_paused + and not self.engine.won + and not self._game_concluded + ): self._checkpoint_ticks += 1 if self._checkpoint_ticks >= self.CHECKPOINT_TICKS: self._checkpoint_ticks = 0 @@ -403,10 +490,13 @@ class FreeCellTableView: return try: 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 "" + paused_tag = ( + t("sol_hud_paused_tag") + if (self.engine.is_timer_paused and not self.engine.won and not self._game_concluded) + else "" + ) diff_label = t(f"sol_diff_short_{self.difficulty}") 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: @@ -415,13 +505,17 @@ class FreeCellTableView: def _sync_buttons(self): if not self._canvas_alive(): return - locked = self.engine.won or self._auto_running or (self._modal_overlay is not None) + locked = self._is_ui_locked() self.undo_btn.set_enabled((not locked) and self.engine.can_undo) self.undo_all_btn.set_enabled((not locked) and self.engine.can_undo_all) self.hint_btn.set_enabled(not locked) 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") + self.new_btn.set_enabled((not self._auto_running) and (self._fx_overlay is None) and (self._modal_overlay is None)) + new_lbl = ( + t("sol_btn_forfeit") + if (self.engine.moves > 0 and not self.engine.won and not self._game_concluded) + else t("sol_btn_new_deal") + ) prev_w = self.new_btn.pixel_width self.new_btn.set_text(new_lbl) if self.new_btn.pixel_width != prev_w: @@ -488,6 +582,8 @@ class FreeCellTableView: duration_ms: int = 115, after_cb=None, ) -> bool: + if self.hover_zoom is not None: + self.hover_zoom.cancel() if self.animator: self.animator.flush() before_pos = self._snapshot_card_positions() @@ -536,8 +632,10 @@ class FreeCellTableView: return True def _on_canvas_configure(self, _event=None): - if not self._canvas_alive(): + if not self._canvas_alive() or self._fx_overlay is not None: return + if self.hover_zoom is not None: + self.hover_zoom.cancel() if self.animator: self.animator.flush() if self._resize_job is not None: @@ -563,7 +661,7 @@ class FreeCellTableView: def _recompute_and_draw(self): self._resize_job = None - if not self._canvas_alive(): + if not self._canvas_alive() or self._fx_overlay is not None: return cw = max(680, self.canvas.winfo_width()) ch = max(420, self.canvas.winfo_height()) @@ -662,9 +760,11 @@ class FreeCellTableView: ): if not self._canvas_alive(): return - bg_ids = set(self.canvas.find_withtag("table_bg_slice")) + keep_ids = set(self.canvas.find_withtag("table_bg_slice")) | set( + self.canvas.find_withtag("modal_dim_veil") + ) for item_id in self.canvas.find_all(): - if item_id not in bg_ids: + if item_id not in keep_ids: self.canvas.delete(item_id) self._canvas_ui_refs.clear() cw, ch = self.card_size @@ -694,7 +794,6 @@ class FreeCellTableView: hint = self._active_hint - # 1. Obere linke Hälfte: 4 Freie Zellen for fc_i in range(4): fx = self._fc_x[fc_i] fc_hl = ACCENT_GOTH if fc_i in valid_drag_fc else None @@ -711,9 +810,8 @@ class FreeCellTableView: if c is not None and self._card_key(c) in hidden: c = None if c is not None: - self._draw_card_at(c, fx, self._top_y, highlight_color=fc_hl) + self._draw_card_at(c, fx, self._top_y, tags=(f"fc_cell_{fc_i}",), highlight_color=fc_hl) - # 2. Obere rechte Hälfte: 4 Foundations for f_idx, suit in enumerate(SUITS): fx = self._found_x[f_idx] sym = SUIT_SYMBOLS[suit] @@ -728,9 +826,8 @@ class FreeCellTableView: pile = pile[:-1] pile = [c for c in pile if self._card_key(c) not in hidden] if pile: - self._draw_card_at(pile[-1], fx, self._top_y, highlight_color=f_hl) + self._draw_card_at(pile[-1], fx, self._top_y, tags=(f"fc_found_{f_idx}",), highlight_color=f_hl) - # 3. Untere Reihe: 8 Tableau-Spalten self._tableau_card_rects = [[] for _ in range(8)] for col_idx in range(8): @@ -765,16 +862,23 @@ class FreeCellTableView: elif hint.get("dst_col") == col_idx and is_last: c_hl = ACCENT_GOLD - self._draw_card_at(card, tx, cur_y, highlight_color=c_hl) + self._draw_card_at( + card, + tx, + cur_y, + tags=(f"fc_tab_{col_idx}_{c_idx}",), + highlight_color=c_hl, + ) 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 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 not self._game_concluded and self._modal_overlay is None + and self._fx_overlay is None ): p_ph = self.ctx.assets.get_goth_text_photo( t("sol_canvas_paused_banner"), FONT_SIZE_BODY, FONT_COLOR_TITLE_MAIN @@ -787,6 +891,16 @@ class FreeCellTableView: self.canvas.create_image(pcx, pcy, image=box_ph, anchor="center") self.canvas.create_image(pcx, pcy, image=p_ph, anchor="center") + if self.canvas.find_withtag("modal_dim_veil"): + self.canvas.tag_raise("modal_dim_veil") + + if ( + self.hover_zoom is not None + and exclude_source is None + and not hidden + ): + self.hover_zoom.refresh_after_redraw() + self._sync_buttons() def _hit_test(self, x: int, y: int) -> dict | None: @@ -839,7 +953,9 @@ class FreeCellTableView: return None def _on_mouse_down(self, event): - if self.engine.won or self._auto_running or self._modal_overlay is not None: + if self.hover_zoom is not None: + self.hover_zoom.cancel() + if self._is_ui_locked(): return if self.animator and self.animator.is_active: self.animator.flush() @@ -853,15 +969,18 @@ class FreeCellTableView: self.engine.start_timer_if_needed() self._update_hud_text() hit["start_xy"] = (event.x, event.y) + hit["press_ts"] = time.monotonic() self._press_info = hit def _on_mouse_move(self, event): - if not self._press_info: + if not self._press_info or self._fx_overlay is not None: return sx, sy = self._press_info["start_xy"] if not self._dragging: if abs(event.x - sx) < self.DRAG_THRESHOLD_PX and abs(event.y - sy) < self.DRAG_THRESHOLD_PX: return + if self.hover_zoom is not None: + self.hover_zoom.cancel() self._dragging = True self._drag_last_xy = (sx, sy) self.redraw(exclude_source=self._press_info) @@ -933,6 +1052,13 @@ class FreeCellTableView: def _handle_click(self, info: dict): now = time.monotonic() + if is_single_tap_to_move_enabled(): + hold_sec = now - info.get("press_ts", now) + self._last_click_target = None + if hold_sec <= SINGLE_TAP_MAX_HOLD_SEC: + self._smart_auto_move(info) + return + target_id = (info["zone"], info.get("col", -1), info.get("idx", -1)) if self._last_click_target == target_id and (now - self._last_click_ts) <= self.DOUBLE_CLICK_SEC: self._last_click_target = None @@ -942,7 +1068,9 @@ class FreeCellTableView: self._last_click_target = target_id def _on_right_click(self, event): - if self.engine.won or self._auto_running or self._modal_overlay is not None: + if self.hover_zoom is not None: + self.hover_zoom.cancel() + if self._is_ui_locked(): return if self.animator and self.animator.is_active: self.animator.flush() @@ -1089,13 +1217,13 @@ class FreeCellTableView: self._check_deadlock_and_prompt() def _check_deadlock_and_prompt(self): - if self.engine.won or self._auto_running or self._modal_overlay is not None: + if self._is_ui_locked(): return if not self.engine.has_any_meaningful_move(): self._show_deadlock_modal() def _on_undo(self): - if self.engine.won or self._auto_running or self._modal_overlay is not None: + if self._is_ui_locked(): return self._clear_hint() @@ -1108,7 +1236,7 @@ class FreeCellTableView: self._run_animated_action(self.engine.undo, duration_ms=105, after_cb=finish_undo) def _on_undo_all(self): - if self.engine.won or self._auto_running or self._modal_overlay is not None: + if self._is_ui_locked(): return if self.animator: self.animator.flush() @@ -1129,7 +1257,7 @@ class FreeCellTableView: self._active_hint = None def _on_hint(self): - if self.engine.won or self._auto_running or self._modal_overlay is not None: + if self._is_ui_locked(): return if self.animator: self.animator.flush() @@ -1149,11 +1277,11 @@ class FreeCellTableView: def _expire_hint(self): self._hint_job = None self._active_hint = None - if self._canvas_alive(): + if self._canvas_alive() and self._fx_overlay is None: self.redraw() def _start_auto_complete(self): - if not self.engine.can_auto_complete() or self._auto_running: + if not self.engine.can_auto_complete() or self._is_ui_locked(): return if self.animator: self.animator.flush() @@ -1196,11 +1324,11 @@ class FreeCellTableView: self._save_progress() def _on_new_or_forfeit_clicked(self): - if self._auto_running or self._modal_overlay is not None: + if self._auto_running or self._modal_overlay is not None or self._fx_overlay is not None: return if self.animator: self.animator.flush() - if self.engine.won or self.engine.moves == 0: + if self.engine.won or self._game_concluded or self.engine.moves == 0: self._game_concluded = False self.engine.new_game(difficulty=self.difficulty) self._save_progress() @@ -1219,42 +1347,95 @@ class FreeCellTableView: return max(2, int(round(win_xp * SOLO_FORFEIT_XP_RATIO))) def _execute_forfeit(self, penalty: int, go_menu: bool): + if self.hover_zoom is not None: + self.hover_zoom.cancel() pid = self.ctx.profile["id"] prog = Database.get_game_progress(pid, GAME_FOLDER_ID) floor_xp = Progression.get_creator_spirit_v_floor_xp() if prog["ever_reached_deity"] else 0 self._game_concluded = True + self.engine.pause_timer() + dur = self.engine.get_elapsed_seconds() Database.delete_game_state(pid, GAME_FOLDER_ID) Database.record_game_result( pid, variant_key=self.variant_key, won=False, - duration_sec=self.engine.get_elapsed_seconds(), + duration_sec=dur, points_gained=0, ) 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.topbar.level_label.configure(text="") + self.topbar.update_level_xp_text() self.ctx.sounds.play("lose") if self._modal_overlay is not None: - self._modal_overlay.destroy() + try: + self._modal_overlay.destroy() + except Exception: + pass self._modal_overlay = None - if go_menu: - self._cleanup_timers() - if callable(self.on_back_to_menu): - self.on_back_to_menu(t("sol_loss_xp", deducted), False) - else: + self._sync_buttons() + + def _after_lose_fx(): + self._fx_overlay = None + if not self._canvas_alive(): + return + self._show_defeat_result_modal(deducted, dur, prefer_menu=go_menu) + + self._fx_overlay = EndgameFxOverlay.play( + self.ctx.root, + self.ctx.assets, + outcome="lose", + on_continue=_after_lose_fx, + target_canvas=self.canvas, + ) + self._sync_buttons() + + def _show_defeat_result_modal(self, deducted: int, dur: float, prefer_menu: bool): + lines = [ + t( + "sol_win_summary", + self.engine.score, + self.engine.moves, + Database.format_seconds(dur), + t(f"sol_diff_short_{self.difficulty}"), + ), + t("sol_loss_xp", deducted), + ] + + def play_again(): + self._close_active_modal() self._game_concluded = False self.engine.new_game(difficulty=self.difficulty) self._check_window_focus() self._save_progress() - self.status_var.set(t("sol_loss_xp", deducted)) + self.status_var.set("") self.ctx.sounds.play("deal") self.redraw() + def to_menu(): + self._close_active_modal() + self._cleanup_timers() + if callable(self.on_back_to_menu): + self.on_back_to_menu(t("sol_loss_xp", deducted), False) + + self._modal_overlay = SolitaireModalDialog( + self.ctx, + title_txt=t("sol_forfeit_title"), + body_txt="\n".join(lines), + is_danger=True, + buttons=[ + (t("sol_play_again_btn"), "amethyst" if prefer_menu else "fire", play_again), + (t("bj_popup_to_menu_btn"), "fire" if prefer_menu else "amethyst", to_menu), + ], + ) + self._sync_buttons() + def _show_deadlock_modal(self): + if self.hover_zoom is not None: + self.hover_zoom.cancel() self.engine.pause_timer() self._save_progress() penalty = self._compute_forfeit_penalty() @@ -1281,6 +1462,8 @@ class FreeCellTableView: self._sync_buttons() def _show_forfeit_modal(self): + if self.hover_zoom is not None: + self.hover_zoom.cancel() self.engine.pause_timer() self._save_progress() penalty = self._compute_forfeit_penalty() @@ -1299,7 +1482,10 @@ class FreeCellTableView: self._sync_buttons() def _handle_victory(self): + if self.hover_zoom is not None: + self.hover_zoom.cancel() self._game_concluded = True + self.engine.pause_timer() pid = self.ctx.profile["id"] Database.delete_game_state(pid, GAME_FOLDER_ID) dur = self.engine.get_elapsed_seconds() @@ -1320,9 +1506,24 @@ class FreeCellTableView: duration_sec=dur, points_gained=xp_earned, ) - self.topbar.level_label.configure(text="") + self.topbar.update_level_xp_text() self.ctx.sounds.play("win") - self._show_victory_modal(xp_earned, old_lvl, new_lvl, dur) + self._sync_buttons() + + def _after_win_fx(): + self._fx_overlay = None + if not self._canvas_alive(): + return + self._show_victory_modal(xp_earned, old_lvl, new_lvl, dur) + + self._fx_overlay = EndgameFxOverlay.play( + self.ctx.root, + self.ctx.assets, + outcome="win", + on_continue=_after_win_fx, + target_canvas=self.canvas, + ) + self._sync_buttons() def _show_victory_modal(self, xp_earned: int, old_lvl: int, new_lvl: int, dur: float): lines = [ @@ -1349,6 +1550,7 @@ class FreeCellTableView: self.redraw() def to_menu(): + self._close_active_modal() self._cleanup_timers() if callable(self.on_back_to_menu): self.on_back_to_menu() @@ -1357,7 +1559,6 @@ class FreeCellTableView: 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), 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 3fba8ec..8772ae0 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_table_view.py b/games/solitaire/klondike/views/klondike_table_view.py index 0daa544..93f92ab 100644 --- a/games/solitaire/klondike/views/klondike_table_view.py +++ b/games/solitaire/klondike/views/klondike_table_view.py @@ -6,10 +6,14 @@ import time import tkinter as tk from games.solitaire.base.card_animator import CardFlightAnimator +from games.solitaire.base.card_hover_zoom import CardHoverZoom 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_tap_prefs import ( + SINGLE_TAP_MAX_HOLD_SEC, + is_single_tap_to_move_enabled, +) from games.solitaire.base.solitaire_theme import SolitaireTableBgRenderer from games.solitaire.klondike.models.klondike_engine import KlondikeEngine from models.database import Database @@ -17,7 +21,6 @@ from models.progression import Progression from resources.code_res.game_constants import ( ACCENT_GOLD, ACCENT_GOTH, - BG_COLOR, BORDER_COLOR, CELL_BG, ERROR_FG, @@ -34,6 +37,7 @@ from resources.code_res.game_constants import ( TABLE_BG, ) from resources.code_res.i18n import t +from view.widgets.endgame_fx_overlay import EndgameFxOverlay from view.widgets.image_button import ImageButton GAME_FOLDER_ID = "solitaire/klondike" @@ -93,6 +97,8 @@ class KlondikeTableView: self._bind_ids: list[tuple[str, str]] = [] self._auto_running = False self.animator: CardFlightAnimator | None = None + self.hover_zoom: CardHoverZoom | None = None + self._fx_overlay: EndgameFxOverlay | None = None self._bg_renderer = SolitaireTableBgRenderer(self.ctx.assets.res) self._frame_bot_pad: int = 18 self._canvas_ui_refs: list = [] @@ -104,6 +110,7 @@ class KlondikeTableView: self._tableau_y: int = 188 self._tableau_card_rects: list[list[tuple[int, int, int, int]]] = [[] for _ in range(7)] self._waste_top_rect: tuple[int, int, int, int] | None = None + self._waste_shown_entries: list[tuple[SolitaireCard, int, int, int, int, str | None]] = [] self._press_info: dict | None = None self._dragging: bool = False @@ -125,6 +132,15 @@ class KlondikeTableView: d_mult = SOLITAIRE_DIFFICULTIES.get(self.difficulty, SOLITAIRE_DIFFICULTIES[1])["xp_mult"] return self.cfg["xp_mult"] * d_mult + def _is_ui_locked(self) -> bool: + return ( + self.engine.won + or self._game_concluded + or self._auto_running + or (self._modal_overlay is not None) + or (self._fx_overlay is not None) + ) + def _canvas_alive(self) -> bool: if not self._alive: return False @@ -133,6 +149,75 @@ class KlondikeTableView: except Exception: return False + def _can_show_hover_zoom(self) -> bool: + if not self._canvas_alive(): + return False + if self._is_ui_locked() or self._dragging or self._press_info is not None: + return False + if not self._window_active: + return False + if self.animator is not None and self.animator.is_active: + return False + return True + + def _hover_card_probe(self, x: int, y: int) -> dict | None: + cw, ch = self.card_size + + # 1. Sichtbarer Waste-Fächer (von oben nach unten prüfen, damit 3er-Fächer einzeln greifen) + for w_card, x1, y1, x2, y2, next_tag in reversed(self._waste_shown_entries): + if x1 <= x <= x2 and y1 <= y <= y2: + if w_card.face_up: + return { + "card": w_card, + "x": x1, + "y": y1, + "size": self.card_size, + "under_tag": next_tag, + } + return None + + # 2. Foundations (Spalten 3..6) + for f_idx in range(4): + fx = self._col_x[3 + f_idx] + if fx <= x <= fx + cw and self._top_y <= y <= self._top_y + ch: + pile = self.engine.foundations[f_idx] + if pile and pile[-1].face_up: + return { + "card": pile[-1], + "x": fx, + "y": self._top_y, + "size": self.card_size, + "under_tag": None, + } + return None + + # 3. Tableau-Spalten (nur aufgedeckte Karten, verdeckte Karten ignorieren) + for col_idx in range(7): + rects = self._tableau_card_rects[col_idx] + col_cards = self.engine.tableau[col_idx] + for c_idx in range(len(rects) - 1, -1, -1): + if c_idx >= len(col_cards): + continue + x1, y1, x2, y2 = rects[c_idx] + if x1 <= x <= x2 and y1 <= y <= y2: + card = col_cards[c_idx] + if not card.face_up: + return None + next_tag = ( + f"kl_tab_{col_idx}_{c_idx + 1}" + if (c_idx + 1) < len(col_cards) + else None + ) + return { + "card": card, + "x": x1, + "y": y1, + "size": self.card_size, + "under_tag": next_tag, + } + + return None + def _play_table_music(self): for method_name in ("play_ingame_music", "play_table_music"): fn = getattr(self.ctx.sounds, method_name, None) @@ -166,6 +251,11 @@ class KlondikeTableView: def _cleanup_timers(self): self._alive = False self.engine.pause_timer() + if self._fx_overlay is not None: + self._fx_overlay.cancel() + self._fx_overlay = None + if self.hover_zoom is not None: + self.hover_zoom.cancel() if self.animator is not None: self.animator.cancel() for job in ( @@ -212,7 +302,13 @@ class KlondikeTableView: except Exception: return - should_run = has_focus and (self._modal_overlay is None) and (not self.engine.won) + should_run = ( + has_focus + and (self._modal_overlay is None) + and (self._fx_overlay is None) + and (not self._game_concluded) + and (not self.engine.won) + ) prev_paused = self.engine.is_timer_paused self._window_active = has_focus @@ -225,7 +321,7 @@ class KlondikeTableView: if prev_paused != self.engine.is_timer_paused: self._update_hud_text() - if self.animator is None or not self.animator.is_active: + if (self.animator is None or not self.animator.is_active) and self._fx_overlay is None: self.redraw() def _build_ui(self): @@ -235,18 +331,14 @@ class KlondikeTableView: self.topbar = self.ctx.build_game_topbar( self.ctx.root, - t(GAME_TITLE_KEY), - on_game_menu=self._back_to_game_menu, - on_stats=self._open_stats, + stats_endpoint=GAME_FOLDER_ID, stats_enabled=True, - extra_right_text="", on_lang_refresh=self._refresh_lang, ) self.hud_var = tk.StringVar(value="") self.status_var = tk.StringVar(value="") - # 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)) @@ -280,13 +372,21 @@ class KlondikeTableView: btn_norm, btn_purp, self._on_new_or_forfeit_clicked, sound_mgr=self.ctx.sounds, width=104, height=32, style="amethyst", ) - self.bottom_bar.set_buttons([ - self.undo_btn, self.undo_all_btn, self.hint_btn, self.auto_btn, self.new_btn - ]) + self.bottom_bar.set_buttons( + [self.undo_btn, self.undo_all_btn, self.hint_btn, self.auto_btn], + overflow_buttons=[self.new_btn], + ) 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.hover_zoom = CardHoverZoom( + self.ctx.root, + self.canvas, + self.ctx.assets, + probe_fn=self._hover_card_probe, + can_show_fn=self._can_show_hover_zoom, + ) self.canvas.bind("", self._on_canvas_configure) self.canvas.bind("", self._on_canvas_destroy) @@ -306,6 +406,8 @@ class KlondikeTableView: self._update_hud_text() def _on_undo_shortcut(self, _event=None): + if self._fx_overlay is not None or self._game_concluded: + return "break" if self.engine.can_undo and not self._auto_running: if self._modal_overlay is not None: self._close_active_modal() @@ -314,6 +416,8 @@ class KlondikeTableView: return "break" def _on_undo_all_shortcut(self, _event=None): + if self._fx_overlay is not None or self._game_concluded: + return "break" if self.engine.can_undo_all and not self._auto_running: if self._modal_overlay is not None: self._close_active_modal() @@ -346,30 +450,8 @@ class KlondikeTableView: resume_state_json=state_json, ) - def _open_stats(self): - if self.animator: - self.animator.flush() - self.engine.pause_timer() - self._save_progress() - state_json = self.engine.to_json() - variants = Database.get_variants_for_filter(GAME_FOLDER_ID) - cur_vid = next((v["id"] for v in variants if v["variant_key"] == self.variant_key), None) - self._cleanup_timers() - SolitaireStatsView( - self.ctx, - game_folder=GAME_FOLDER_ID, - game_title_key=GAME_TITLE_KEY, - on_back=lambda: KlondikeTableView( - self.ctx, - variant_key=self.variant_key, - difficulty=self.difficulty, - on_back_to_menu=self.on_back_to_menu, - resume_state_json=state_json, - ), - ).show(preselect_variant_id=cur_vid) - def _back_to_game_menu(self): - if self._auto_running: + if self._auto_running or self._fx_overlay is not None: return if self.animator: self.animator.flush() @@ -394,7 +476,12 @@ class KlondikeTableView: self._check_window_focus() self._update_hud_text() - if self.engine.has_timer_started and not self.engine.is_timer_paused and not self.engine.won: + if ( + self.engine.has_timer_started + and not self.engine.is_timer_paused + and not self.engine.won + and not self._game_concluded + ): self._checkpoint_ticks += 1 if self._checkpoint_ticks >= self.CHECKPOINT_TICKS: self._checkpoint_ticks = 0 @@ -410,10 +497,13 @@ class KlondikeTableView: return try: 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 "" + paused_tag = ( + t("sol_hud_paused_tag") + if (self.engine.is_timer_paused and not self.engine.won and not self._game_concluded) + else "" + ) diff_label = t(f"sol_diff_short_{self.difficulty}") 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: @@ -422,13 +512,17 @@ class KlondikeTableView: def _sync_buttons(self): if not self._canvas_alive(): return - locked = self.engine.won or self._auto_running or (self._modal_overlay is not None) + locked = self._is_ui_locked() self.undo_btn.set_enabled((not locked) and self.engine.can_undo) self.undo_all_btn.set_enabled((not locked) and self.engine.can_undo_all) self.hint_btn.set_enabled(not locked) 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") + self.new_btn.set_enabled((not self._auto_running) and (self._fx_overlay is None) and (self._modal_overlay is None)) + new_lbl = ( + t("sol_btn_forfeit") + if (self.engine.moves > 0 and not self.engine.won and not self._game_concluded) + else t("sol_btn_new_deal") + ) prev_w = self.new_btn.pixel_width self.new_btn.set_text(new_lbl) if self.new_btn.pixel_width != prev_w: @@ -523,6 +617,8 @@ class KlondikeTableView: duration_ms: int = 115, after_cb=None, ) -> bool: + if self.hover_zoom is not None: + self.hover_zoom.cancel() if self.animator: self.animator.flush() before_pos = self._snapshot_card_positions() @@ -571,8 +667,10 @@ class KlondikeTableView: return True def _on_canvas_configure(self, _event=None): - if not self._canvas_alive(): + if not self._canvas_alive() or self._fx_overlay is not None: return + if self.hover_zoom is not None: + self.hover_zoom.cancel() if self.animator: self.animator.flush() if self._resize_job is not None: @@ -598,7 +696,7 @@ class KlondikeTableView: def _recompute_and_draw(self): self._resize_job = None - if not self._canvas_alive(): + if not self._canvas_alive() or self._fx_overlay is not None: return cw = max(640, self.canvas.winfo_width()) ch = max(420, self.canvas.winfo_height()) @@ -707,9 +805,11 @@ class KlondikeTableView: ): if not self._canvas_alive(): return - bg_ids = set(self.canvas.find_withtag("table_bg_slice")) + keep_ids = set(self.canvas.find_withtag("table_bg_slice")) | set( + self.canvas.find_withtag("modal_dim_veil") + ) for item_id in self.canvas.find_all(): - if item_id not in bg_ids: + if item_id not in keep_ids: self.canvas.delete(item_id) self._canvas_ui_refs.clear() cw, ch = self.card_size @@ -751,7 +851,7 @@ class KlondikeTableView: ) if vis_stock: - self._draw_card_at(vis_stock[-1], sx, self._top_y, highlight_color=stock_hl) + self._draw_card_at(vis_stock[-1], sx, self._top_y, tags=("kl_stock",), highlight_color=stock_hl) cycles_left = max(0, self.engine.MAX_STAGNANT_CYCLES - self.engine.stagnant_cycles) if self.engine.redeal_limit is not None: rd_left = max(0, self.engine.redeal_limit - self.engine.redeals_used) @@ -766,7 +866,7 @@ class KlondikeTableView: fill=ACCENT_GOLD, ) - # 2. Waste (Spalte 1) + # 2. Waste (Spalte 1) inkl. Z-Order-Tags für den 3er-Fächer wx = self._col_x[1] self._draw_slot(wx, self._top_y) waste_cards = list(self.engine.waste) @@ -775,6 +875,7 @@ class KlondikeTableView: waste_cards = [c for c in waste_cards if self._card_key(c) not in hidden] self._waste_top_rect = None + self._waste_shown_entries = [] if waste_cards: visible_n = min(3, len(waste_cards)) if self.engine.draw_count == 3 else 1 shown = waste_cards[-visible_n:] @@ -787,7 +888,13 @@ class KlondikeTableView: if (is_top and hint and hint.get("type") in ("waste_to_foundation", "waste_to_tableau")) else None ) - self._draw_card_at(w_card, cx, self._top_y, highlight_color=w_hl) + w_tag = f"kl_waste_{idx}" + next_w_tag = f"kl_waste_{idx + 1}" if not is_top else None + self._draw_card_at(w_card, cx, self._top_y, tags=(w_tag,), highlight_color=w_hl) + hit_x2 = (cx + cw) if is_top else (cx + fan_dx) + self._waste_shown_entries.append( + (w_card, cx, self._top_y, hit_x2, self._top_y + ch, next_w_tag) + ) if is_top: self._waste_top_rect = (cx, self._top_y, cx + cw, self._top_y + ch) @@ -808,9 +915,11 @@ class KlondikeTableView: f_pile = f_pile[:-1] f_pile = [c for c in f_pile if self._card_key(c) not in hidden] if f_pile: - self._draw_card_at(f_pile[-1], fx, self._top_y, highlight_color=f_hl) + self._draw_card_at( + f_pile[-1], fx, self._top_y, tags=(f"kl_found_{f_idx}",), highlight_color=f_hl + ) - # 4. Tableau (Spalten 0..6) + # 4. Tableau (Spalten 0..6) mit Z-Order-Tags pro Karte self._tableau_card_rects = [[] for _ in range(7)] for col_idx in range(7): @@ -845,7 +954,13 @@ class KlondikeTableView: elif hint.get("dst_col") == col_idx and is_last: c_hl = ACCENT_GOLD - self._draw_card_at(card, tx, cur_y, highlight_color=c_hl) + self._draw_card_at( + card, + tx, + cur_y, + tags=(f"kl_tab_{col_idx}_{c_idx}",), + highlight_color=c_hl, + ) 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)) @@ -854,7 +969,9 @@ class KlondikeTableView: self.engine.has_timer_started and not self._window_active and not self.engine.won + and not self._game_concluded and self._modal_overlay is None + and self._fx_overlay is None ): p_ph = self.ctx.assets.get_goth_text_photo( t("sol_canvas_paused_banner"), FONT_SIZE_BODY, FONT_COLOR_TITLE_MAIN @@ -867,6 +984,16 @@ class KlondikeTableView: self.canvas.create_image(pcx, pcy, image=box_ph, anchor="center") self.canvas.create_image(pcx, pcy, image=p_ph, anchor="center") + if self.canvas.find_withtag("modal_dim_veil"): + self.canvas.tag_raise("modal_dim_veil") + + if ( + self.hover_zoom is not None + and exclude_source is None + and not hidden + ): + self.hover_zoom.refresh_after_redraw() + self._sync_buttons() def _hit_test(self, x: int, y: int) -> dict | None: @@ -919,7 +1046,9 @@ class KlondikeTableView: return None def _on_mouse_down(self, event): - if self.engine.won or self._auto_running or self._modal_overlay is not None: + if self.hover_zoom is not None: + self.hover_zoom.cancel() + if self._is_ui_locked(): return if self.animator and self.animator.is_active: self.animator.flush() @@ -933,15 +1062,18 @@ class KlondikeTableView: self.engine.start_timer_if_needed() self._update_hud_text() hit["start_xy"] = (event.x, event.y) + hit["press_ts"] = time.monotonic() self._press_info = hit def _on_mouse_move(self, event): - if not self._press_info or self._press_info.get("zone") == "stock": + if not self._press_info or self._press_info.get("zone") == "stock" or self._fx_overlay is not None: return sx, sy = self._press_info["start_xy"] if not self._dragging: if abs(event.x - sx) < self.DRAG_THRESHOLD_PX and abs(event.y - sy) < self.DRAG_THRESHOLD_PX: return + if self.hover_zoom is not None: + self.hover_zoom.cancel() self._dragging = True self._drag_last_xy = (sx, sy) self.redraw(exclude_source=self._press_info) @@ -1032,6 +1164,13 @@ class KlondikeTableView: return now = time.monotonic() + if is_single_tap_to_move_enabled(): + hold_sec = now - info.get("press_ts", now) + self._last_click_target = None + if hold_sec <= SINGLE_TAP_MAX_HOLD_SEC: + self._smart_auto_move(info) + return + target_id = (zone, info.get("col", -1), info.get("idx", -1)) if self._last_click_target == target_id and (now - self._last_click_ts) <= self.DOUBLE_CLICK_SEC: self._last_click_target = None @@ -1041,7 +1180,9 @@ class KlondikeTableView: self._last_click_target = target_id def _on_right_click(self, event): - if self.engine.won or self._auto_running or self._modal_overlay is not None: + if self.hover_zoom is not None: + self.hover_zoom.cancel() + if self._is_ui_locked(): return if self.animator and self.animator.is_active: self.animator.flush() @@ -1150,13 +1291,13 @@ class KlondikeTableView: self._check_deadlock_and_prompt() def _check_deadlock_and_prompt(self): - if self.engine.won or self._auto_running or self._modal_overlay is not None: + if self._is_ui_locked(): return if not self.engine.has_any_meaningful_move(): self._show_deadlock_modal() def _on_undo(self): - if self.engine.won or self._auto_running or self._modal_overlay is not None: + if self._is_ui_locked(): return self._clear_hint() @@ -1169,7 +1310,7 @@ class KlondikeTableView: self._run_animated_action(self.engine.undo, duration_ms=105, after_cb=finish_undo) def _on_undo_all(self): - if self.engine.won or self._auto_running or self._modal_overlay is not None: + if self._is_ui_locked(): return if self.animator: self.animator.flush() @@ -1190,7 +1331,7 @@ class KlondikeTableView: self._active_hint = None def _on_hint(self): - if self.engine.won or self._auto_running or self._modal_overlay is not None: + if self._is_ui_locked(): return if self.animator: self.animator.flush() @@ -1210,11 +1351,11 @@ class KlondikeTableView: def _expire_hint(self): self._hint_job = None self._active_hint = None - if self._canvas_alive(): + if self._canvas_alive() and self._fx_overlay is None: self.redraw() def _start_auto_complete(self): - if not self.engine.can_auto_complete() or self._auto_running: + if not self.engine.can_auto_complete() or self._is_ui_locked(): return if self.animator: self.animator.flush() @@ -1257,11 +1398,11 @@ class KlondikeTableView: self._save_progress() def _on_new_or_forfeit_clicked(self): - if self._auto_running or self._modal_overlay is not None: + if self._auto_running or self._modal_overlay is not None or self._fx_overlay is not None: return if self.animator: self.animator.flush() - if self.engine.won or self.engine.moves == 0: + if self.engine.won or self._game_concluded or self.engine.moves == 0: self._game_concluded = False self.engine.new_game(draw_count=self.cfg["draw_count"], difficulty=self.difficulty) self._save_progress() @@ -1280,42 +1421,95 @@ class KlondikeTableView: return max(2, int(round(win_xp * SOLO_FORFEIT_XP_RATIO))) def _execute_forfeit(self, penalty: int, go_menu: bool): + if self.hover_zoom is not None: + self.hover_zoom.cancel() pid = self.ctx.profile["id"] prog = Database.get_game_progress(pid, GAME_FOLDER_ID) floor_xp = Progression.get_creator_spirit_v_floor_xp() if prog["ever_reached_deity"] else 0 self._game_concluded = True + self.engine.pause_timer() + dur = self.engine.get_elapsed_seconds() Database.delete_game_state(pid, GAME_FOLDER_ID) Database.record_game_result( pid, variant_key=self.variant_key, won=False, - duration_sec=self.engine.get_elapsed_seconds(), + duration_sec=dur, points_gained=0, ) 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.topbar.level_label.configure(text="") + self.topbar.update_level_xp_text() self.ctx.sounds.play("lose") if self._modal_overlay is not None: - self._modal_overlay.destroy() + try: + self._modal_overlay.destroy() + except Exception: + pass self._modal_overlay = None - if go_menu: - self._cleanup_timers() - if callable(self.on_back_to_menu): - self.on_back_to_menu(t("sol_loss_xp", deducted), False) - else: + self._sync_buttons() + + def _after_lose_fx(): + self._fx_overlay = None + if not self._canvas_alive(): + return + self._show_defeat_result_modal(deducted, dur, prefer_menu=go_menu) + + self._fx_overlay = EndgameFxOverlay.play( + self.ctx.root, + self.ctx.assets, + outcome="lose", + on_continue=_after_lose_fx, + target_canvas=self.canvas, + ) + self._sync_buttons() + + def _show_defeat_result_modal(self, deducted: int, dur: float, prefer_menu: bool): + lines = [ + t( + "sol_win_summary", + self.engine.score, + self.engine.moves, + Database.format_seconds(dur), + t(f"sol_diff_short_{self.difficulty}"), + ), + t("sol_loss_xp", deducted), + ] + + def play_again(): + 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() self._save_progress() - self.status_var.set(t("sol_loss_xp", deducted)) + self.status_var.set("") self.ctx.sounds.play("deal") self.redraw() + def to_menu(): + self._close_active_modal() + self._cleanup_timers() + if callable(self.on_back_to_menu): + self.on_back_to_menu(t("sol_loss_xp", deducted), False) + + self._modal_overlay = SolitaireModalDialog( + self.ctx, + title_txt=t("sol_forfeit_title"), + body_txt="\n".join(lines), + is_danger=True, + buttons=[ + (t("sol_play_again_btn"), "amethyst" if prefer_menu else "fire", play_again), + (t("bj_popup_to_menu_btn"), "fire" if prefer_menu else "amethyst", to_menu), + ], + ) + self._sync_buttons() + def _show_deadlock_modal(self): + if self.hover_zoom is not None: + self.hover_zoom.cancel() self.engine.pause_timer() self._save_progress() penalty = self._compute_forfeit_penalty() @@ -1342,6 +1536,8 @@ class KlondikeTableView: self._sync_buttons() def _show_forfeit_modal(self): + if self.hover_zoom is not None: + self.hover_zoom.cancel() self.engine.pause_timer() self._save_progress() penalty = self._compute_forfeit_penalty() @@ -1360,7 +1556,10 @@ class KlondikeTableView: self._sync_buttons() def _handle_victory(self): + if self.hover_zoom is not None: + self.hover_zoom.cancel() self._game_concluded = True + self.engine.pause_timer() pid = self.ctx.profile["id"] Database.delete_game_state(pid, GAME_FOLDER_ID) dur = self.engine.get_elapsed_seconds() @@ -1381,9 +1580,24 @@ class KlondikeTableView: duration_sec=dur, points_gained=xp_earned, ) - self.topbar.level_label.configure(text="") + self.topbar.update_level_xp_text() self.ctx.sounds.play("win") - self._show_victory_modal(xp_earned, old_lvl, new_lvl, dur) + self._sync_buttons() + + def _after_win_fx(): + self._fx_overlay = None + if not self._canvas_alive(): + return + self._show_victory_modal(xp_earned, old_lvl, new_lvl, dur) + + self._fx_overlay = EndgameFxOverlay.play( + self.ctx.root, + self.ctx.assets, + outcome="win", + on_continue=_after_win_fx, + target_canvas=self.canvas, + ) + self._sync_buttons() def _show_victory_modal(self, xp_earned: int, old_lvl: int, new_lvl: int, dur: float): lines = [ @@ -1410,6 +1624,7 @@ class KlondikeTableView: self.redraw() def to_menu(): + self._close_active_modal() self._cleanup_timers() if callable(self.on_back_to_menu): self.on_back_to_menu() @@ -1418,7 +1633,6 @@ class KlondikeTableView: 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), 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 a4350e7..0610224 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_table_view.py b/games/solitaire/spider_solitaire/views/spider_table_view.py index eb689bb..a7e9989 100644 --- a/games/solitaire/spider_solitaire/views/spider_table_view.py +++ b/games/solitaire/spider_solitaire/views/spider_table_view.py @@ -6,10 +6,14 @@ import time import tkinter as tk from games.solitaire.base.card_animator import CardFlightAnimator +from games.solitaire.base.card_hover_zoom import CardHoverZoom 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_tap_prefs import ( + SINGLE_TAP_MAX_HOLD_SEC, + is_single_tap_to_move_enabled, +) from games.solitaire.base.solitaire_theme import SolitaireTableBgRenderer from games.solitaire.spider_solitaire.models.spider_engine import SpiderEngine from models.database import Database @@ -17,7 +21,6 @@ from models.progression import Progression from resources.code_res.game_constants import ( ACCENT_GOLD, ACCENT_GOTH, - BG_COLOR, BORDER_COLOR, CELL_BG, ERROR_FG, @@ -32,6 +35,7 @@ from resources.code_res.game_constants import ( TABLE_BG, ) from resources.code_res.i18n import t +from view.widgets.endgame_fx_overlay import EndgameFxOverlay from view.widgets.image_button import ImageButton GAME_FOLDER_ID = "solitaire/spider_solitaire" @@ -86,6 +90,8 @@ class SpiderTableView: self._resize_job: str | None = None self._bind_ids: list[tuple[str, str]] = [] self.animator: CardFlightAnimator | None = None + self.hover_zoom: CardHoverZoom | None = None + self._fx_overlay: EndgameFxOverlay | None = None self._bg_renderer = SolitaireTableBgRenderer(self.ctx.assets.res) self._frame_bot_pad: int = 18 self._canvas_ui_refs: list = [] @@ -118,6 +124,14 @@ class SpiderTableView: d_mult = SOLITAIRE_DIFFICULTIES.get(self.difficulty, SOLITAIRE_DIFFICULTIES[1])["xp_mult"] return self.cfg["xp_mult"] * d_mult + def _is_ui_locked(self) -> bool: + return ( + self.engine.won + or self._game_concluded + or (self._modal_overlay is not None) + or (self._fx_overlay is not None) + ) + def _canvas_alive(self) -> bool: if not self._alive: return False @@ -126,6 +140,62 @@ class SpiderTableView: except Exception: return False + def _can_show_hover_zoom(self) -> bool: + if not self._canvas_alive(): + return False + if self._is_ui_locked() or self._dragging or self._press_info is not None: + return False + if not self._window_active: + return False + if self.animator is not None and self.animator.is_active: + return False + return True + + def _hover_card_probe(self, x: int, y: int) -> dict | None: + cw, ch = self.card_size + + # 1. Abgeschlossene Sequenzen oben rechts (Spalten 2..9) + for r_slot in range(min(8, len(self.engine.completed_runs))): + rx = self._col_x[2 + r_slot] + if rx <= x <= rx + cw and self._top_y <= y <= self._top_y + ch: + run = self.engine.completed_runs[r_slot] + if run and run[0].face_up: + return { + "card": run[0], + "x": rx, + "y": self._top_y, + "size": self.card_size, + "under_tag": None, + } + return None + + # 2. 10 Tableau-Spalten (alle offenen Karten, auch nicht-ziehbare) + for col_idx in range(10): + rects = self._tableau_card_rects[col_idx] + col_cards = self.engine.tableau[col_idx] + for c_idx in range(len(rects) - 1, -1, -1): + if c_idx >= len(col_cards): + continue + x1, y1, x2, y2 = rects[c_idx] + if x1 <= x <= x2 and y1 <= y <= y2: + card = col_cards[c_idx] + if not card.face_up: + return None + next_tag = ( + f"sp_tab_{col_idx}_{c_idx + 1}" + if (c_idx + 1) < len(col_cards) + else None + ) + return { + "card": card, + "x": x1, + "y": y1, + "size": self.card_size, + "under_tag": next_tag, + } + + return None + def _play_table_music(self): for method_name in ("play_ingame_music", "play_table_music"): fn = getattr(self.ctx.sounds, method_name, None) @@ -159,6 +229,11 @@ class SpiderTableView: def _cleanup_timers(self): self._alive = False self.engine.pause_timer() + if self._fx_overlay is not None: + self._fx_overlay.cancel() + self._fx_overlay = None + if self.hover_zoom is not None: + self.hover_zoom.cancel() if self.animator is not None: self.animator.cancel() for job in ( @@ -204,7 +279,13 @@ class SpiderTableView: except Exception: return - should_run = has_focus and (self._modal_overlay is None) and (not self.engine.won) + should_run = ( + has_focus + and (self._modal_overlay is None) + and (self._fx_overlay is None) + and (not self._game_concluded) + and (not self.engine.won) + ) prev_paused = self.engine.is_timer_paused self._window_active = has_focus @@ -217,7 +298,7 @@ class SpiderTableView: if prev_paused != self.engine.is_timer_paused: self._update_hud_text() - if self.animator is None or not self.animator.is_active: + if (self.animator is None or not self.animator.is_active) and self._fx_overlay is None: self.redraw() def _build_ui(self): @@ -227,18 +308,14 @@ class SpiderTableView: self.topbar = self.ctx.build_game_topbar( self.ctx.root, - t(GAME_TITLE_KEY), - on_game_menu=self._back_to_game_menu, - on_stats=self._open_stats, + stats_endpoint=GAME_FOLDER_ID, stats_enabled=True, - extra_right_text="", on_lang_refresh=self._refresh_lang, ) self.hud_var = tk.StringVar(value="") self.status_var = tk.StringVar(value="") - # 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)) @@ -266,13 +343,21 @@ class SpiderTableView: btn_norm, btn_purp, self._on_new_or_forfeit_clicked, sound_mgr=self.ctx.sounds, width=104, height=32, style="amethyst", ) - self.bottom_bar.set_buttons([ - self.undo_btn, self.undo_all_btn, self.hint_btn, self.new_btn - ]) + self.bottom_bar.set_buttons( + [self.undo_btn, self.undo_all_btn, self.hint_btn], + overflow_buttons=[self.new_btn], + ) 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.hover_zoom = CardHoverZoom( + self.ctx.root, + self.canvas, + self.ctx.assets, + probe_fn=self._hover_card_probe, + can_show_fn=self._can_show_hover_zoom, + ) self.canvas.bind("", self._on_canvas_configure) self.canvas.bind("", self._on_canvas_destroy) @@ -292,6 +377,8 @@ class SpiderTableView: self._update_hud_text() def _on_undo_shortcut(self, _event=None): + if self._fx_overlay is not None or self._game_concluded: + return "break" if self.engine.can_undo: if self._modal_overlay is not None: self._close_active_modal() @@ -300,6 +387,8 @@ class SpiderTableView: return "break" def _on_undo_all_shortcut(self, _event=None): + if self._fx_overlay is not None or self._game_concluded: + return "break" if self.engine.can_undo_all: if self._modal_overlay is not None: self._close_active_modal() @@ -332,29 +421,9 @@ class SpiderTableView: resume_state_json=state_json, ) - def _open_stats(self): - if self.animator: - self.animator.flush() - self.engine.pause_timer() - self._save_progress() - state_json = self.engine.to_json() - variants = Database.get_variants_for_filter(GAME_FOLDER_ID) - cur_vid = next((v["id"] for v in variants if v["variant_key"] == self.variant_key), None) - self._cleanup_timers() - SolitaireStatsView( - self.ctx, - game_folder=GAME_FOLDER_ID, - game_title_key=GAME_TITLE_KEY, - on_back=lambda: SpiderTableView( - self.ctx, - variant_key=self.variant_key, - difficulty=self.difficulty, - on_back_to_menu=self.on_back_to_menu, - resume_state_json=state_json, - ), - ).show(preselect_variant_id=cur_vid) - def _back_to_game_menu(self): + if self._fx_overlay is not None: + return if self.animator: self.animator.flush() self.engine.pause_timer() @@ -378,7 +447,12 @@ class SpiderTableView: self._check_window_focus() self._update_hud_text() - if self.engine.has_timer_started and not self.engine.is_timer_paused and not self.engine.won: + if ( + self.engine.has_timer_started + and not self.engine.is_timer_paused + and not self.engine.won + and not self._game_concluded + ): self._checkpoint_ticks += 1 if self._checkpoint_ticks >= self.CHECKPOINT_TICKS: self._checkpoint_ticks = 0 @@ -394,10 +468,13 @@ class SpiderTableView: return try: 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 "" + paused_tag = ( + t("sol_hud_paused_tag") + if (self.engine.is_timer_paused and not self.engine.won and not self._game_concluded) + else "" + ) diff_label = t(f"sol_diff_short_{self.difficulty}") 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: @@ -406,11 +483,16 @@ class SpiderTableView: def _sync_buttons(self): if not self._canvas_alive(): return - locked = self.engine.won or (self._modal_overlay is not None) + locked = self._is_ui_locked() self.undo_btn.set_enabled((not locked) and self.engine.can_undo) 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") + self.new_btn.set_enabled((self._fx_overlay is None) and (self._modal_overlay is None)) + new_lbl = ( + t("sol_btn_forfeit") + if (self.engine.moves > 0 and not self.engine.won and not self._game_concluded) + else t("sol_btn_new_deal") + ) prev_w = self.new_btn.pixel_width self.new_btn.set_text(new_lbl) if self.new_btn.pixel_width != prev_w: @@ -498,6 +580,8 @@ class SpiderTableView: duration_ms: int = 120, after_cb=None, ) -> bool: + if self.hover_zoom is not None: + self.hover_zoom.cancel() if self.animator: self.animator.flush() before_pos = self._snapshot_card_positions() @@ -546,8 +630,10 @@ class SpiderTableView: return True def _on_canvas_configure(self, _event=None): - if not self._canvas_alive(): + if not self._canvas_alive() or self._fx_overlay is not None: return + if self.hover_zoom is not None: + self.hover_zoom.cancel() if self.animator: self.animator.flush() if self._resize_job is not None: @@ -573,7 +659,7 @@ class SpiderTableView: def _recompute_and_draw(self): self._resize_job = None - if not self._canvas_alive(): + if not self._canvas_alive() or self._fx_overlay is not None: return cw = max(720, self.canvas.winfo_width()) ch = max(440, self.canvas.winfo_height()) @@ -679,9 +765,11 @@ class SpiderTableView: ): if not self._canvas_alive(): return - bg_ids = set(self.canvas.find_withtag("table_bg_slice")) + keep_ids = set(self.canvas.find_withtag("table_bg_slice")) | set( + self.canvas.find_withtag("modal_dim_veil") + ) for item_id in self.canvas.find_all(): - if item_id not in bg_ids: + if item_id not in keep_ids: self.canvas.delete(item_id) self._canvas_ui_refs.clear() cw, ch = self.card_size @@ -725,7 +813,9 @@ class SpiderTableView: hl = stock_hl if is_top_pack else None if is_top_pack and not can_deal_now and deal_reason == "empty_column": hl = ERROR_FG - self._draw_card_at(vis_packs[0][0], px, self._top_y, highlight_color=hl) + self._draw_card_at( + vis_packs[0][0], px, self._top_y, tags=(f"sp_stock_{slot_i}",), highlight_color=hl + ) last_px = self._stock_pack_x(len(vis_packs) - 1) self._stock_bbox = (sx0, self._top_y, last_px + cw, self._top_y + ch) @@ -746,9 +836,11 @@ 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: - self._draw_card_at(vis_run[0], rx, self._top_y, highlight_color=ACCENT_GOLD) + self._draw_card_at( + vis_run[0], rx, self._top_y, tags=(f"sp_run_{r_slot}",), highlight_color=ACCENT_GOLD + ) - # 3. Untere Reihe: 10 Tableau-Spalten + # 3. Untere Reihe: 10 Tableau-Spalten mit Z-Order-Tags pro Karte self._tableau_card_rects = [[] for _ in range(10)] need_fill_warning = bool(self.engine.stock_deals) and self.engine.has_empty_column() @@ -793,6 +885,7 @@ class SpiderTableView: card, tx, cur_y, + tags=(f"sp_tab_{col_idx}_{c_idx}",), highlight_color=c_hl, dim_non_movable=(card.face_up and c_idx < movable_from), ) @@ -804,7 +897,9 @@ class SpiderTableView: self.engine.has_timer_started and not self._window_active and not self.engine.won + and not self._game_concluded and self._modal_overlay is None + and self._fx_overlay is None ): p_ph = self.ctx.assets.get_goth_text_photo( t("sol_canvas_paused_banner"), FONT_SIZE_BODY, FONT_COLOR_TITLE_MAIN @@ -817,6 +912,16 @@ class SpiderTableView: self.canvas.create_image(pcx, pcy, image=box_ph, anchor="center") self.canvas.create_image(pcx, pcy, image=p_ph, anchor="center") + if self.canvas.find_withtag("modal_dim_veil"): + self.canvas.tag_raise("modal_dim_veil") + + if ( + self.hover_zoom is not None + and exclude_source is None + and not hidden + ): + self.hover_zoom.refresh_after_redraw() + self._sync_buttons() def _hit_test(self, x: int, y: int) -> dict | None: @@ -845,7 +950,9 @@ class SpiderTableView: return None def _on_mouse_down(self, event): - if self.engine.won or self._modal_overlay is not None: + if self.hover_zoom is not None: + self.hover_zoom.cancel() + if self._is_ui_locked(): return if self.animator and self.animator.is_active: self.animator.flush() @@ -859,15 +966,18 @@ class SpiderTableView: self.engine.start_timer_if_needed() self._update_hud_text() hit["start_xy"] = (event.x, event.y) + hit["press_ts"] = time.monotonic() self._press_info = hit def _on_mouse_move(self, event): - if not self._press_info or self._press_info.get("zone") == "stock": + if not self._press_info or self._press_info.get("zone") == "stock" or self._fx_overlay is not None: return sx, sy = self._press_info["start_xy"] if not self._dragging: if abs(event.x - sx) < self.DRAG_THRESHOLD_PX and abs(event.y - sy) < self.DRAG_THRESHOLD_PX: return + if self.hover_zoom is not None: + self.hover_zoom.cancel() self._dragging = True self._drag_last_xy = (sx, sy) self.redraw(exclude_source=self._press_info) @@ -958,6 +1068,13 @@ class SpiderTableView: return now = time.monotonic() + if is_single_tap_to_move_enabled(): + hold_sec = now - info.get("press_ts", now) + self._last_click_target = None + if hold_sec <= SINGLE_TAP_MAX_HOLD_SEC: + self._smart_auto_move(info) + return + target_id = (info["zone"], info.get("col", -1), info.get("idx", -1)) if self._last_click_target == target_id and (now - self._last_click_ts) <= self.DOUBLE_CLICK_SEC: self._last_click_target = None @@ -967,7 +1084,9 @@ class SpiderTableView: self._last_click_target = target_id def _on_right_click(self, event): - if self.engine.won or self._modal_overlay is not None: + if self.hover_zoom is not None: + self.hover_zoom.cancel() + if self._is_ui_locked(): return if self.animator and self.animator.is_active: self.animator.flush() @@ -1057,13 +1176,13 @@ class SpiderTableView: self._check_deadlock_and_prompt() def _check_deadlock_and_prompt(self): - if self.engine.won or self._modal_overlay is not None: + if self._is_ui_locked(): return if not self.engine.has_any_meaningful_move(): self._show_deadlock_modal() def _on_undo(self): - if self.engine.won or self._modal_overlay is not None: + if self._is_ui_locked(): return self._clear_hint() @@ -1076,7 +1195,7 @@ class SpiderTableView: self._run_animated_action(self.engine.undo, duration_ms=110, after_cb=finish_undo) def _on_undo_all(self): - if self.engine.won or self._modal_overlay is not None: + if self._is_ui_locked(): return if self.animator: self.animator.flush() @@ -1097,7 +1216,7 @@ class SpiderTableView: self._active_hint = None def _on_hint(self): - if self.engine.won or self._modal_overlay is not None: + if self._is_ui_locked(): return if self.animator: self.animator.flush() @@ -1117,15 +1236,15 @@ class SpiderTableView: def _expire_hint(self): self._hint_job = None self._active_hint = None - if self._canvas_alive(): + if self._canvas_alive() and self._fx_overlay is None: self.redraw() def _on_new_or_forfeit_clicked(self): - if self._modal_overlay is not None: + if self._modal_overlay is not None or self._fx_overlay is not None: return if self.animator: self.animator.flush() - if self.engine.won or self.engine.moves == 0: + if self.engine.won or self._game_concluded or self.engine.moves == 0: self._game_concluded = False self.engine.new_game(variant_key=self.variant_key, difficulty=self.difficulty) self._save_progress() @@ -1144,42 +1263,95 @@ class SpiderTableView: return max(2, int(round(win_xp * SOLO_FORFEIT_XP_RATIO))) def _execute_forfeit(self, penalty: int, go_menu: bool): + if self.hover_zoom is not None: + self.hover_zoom.cancel() pid = self.ctx.profile["id"] prog = Database.get_game_progress(pid, GAME_FOLDER_ID) floor_xp = Progression.get_creator_spirit_v_floor_xp() if prog["ever_reached_deity"] else 0 self._game_concluded = True + self.engine.pause_timer() + dur = self.engine.get_elapsed_seconds() Database.delete_game_state(pid, GAME_FOLDER_ID) Database.record_game_result( pid, variant_key=self.variant_key, won=False, - duration_sec=self.engine.get_elapsed_seconds(), + duration_sec=dur, points_gained=0, ) 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.topbar.level_label.configure(text="") + self.topbar.update_level_xp_text() self.ctx.sounds.play("lose") if self._modal_overlay is not None: - self._modal_overlay.destroy() + try: + self._modal_overlay.destroy() + except Exception: + pass self._modal_overlay = None - if go_menu: - self._cleanup_timers() - if callable(self.on_back_to_menu): - self.on_back_to_menu(t("sol_loss_xp", deducted), False) - else: + self._sync_buttons() + + def _after_lose_fx(): + self._fx_overlay = None + if not self._canvas_alive(): + return + self._show_defeat_result_modal(deducted, dur, prefer_menu=go_menu) + + self._fx_overlay = EndgameFxOverlay.play( + self.ctx.root, + self.ctx.assets, + outcome="lose", + on_continue=_after_lose_fx, + target_canvas=self.canvas, + ) + self._sync_buttons() + + def _show_defeat_result_modal(self, deducted: int, dur: float, prefer_menu: bool): + lines = [ + t( + "sol_win_summary", + self.engine.score, + self.engine.moves, + Database.format_seconds(dur), + t(f"sol_diff_short_{self.difficulty}"), + ), + t("sol_loss_xp", deducted), + ] + + def play_again(): + self._close_active_modal() self._game_concluded = False self.engine.new_game(variant_key=self.variant_key, difficulty=self.difficulty) self._check_window_focus() self._save_progress() - self.status_var.set(t("sol_loss_xp", deducted)) + self.status_var.set("") self.ctx.sounds.play("deal") self.redraw() + def to_menu(): + self._close_active_modal() + self._cleanup_timers() + if callable(self.on_back_to_menu): + self.on_back_to_menu(t("sol_loss_xp", deducted), False) + + self._modal_overlay = SolitaireModalDialog( + self.ctx, + title_txt=t("sol_forfeit_title"), + body_txt="\n".join(lines), + is_danger=True, + buttons=[ + (t("sol_play_again_btn"), "amethyst" if prefer_menu else "fire", play_again), + (t("bj_popup_to_menu_btn"), "fire" if prefer_menu else "amethyst", to_menu), + ], + ) + self._sync_buttons() + def _show_deadlock_modal(self): + if self.hover_zoom is not None: + self.hover_zoom.cancel() self.engine.pause_timer() self._save_progress() penalty = self._compute_forfeit_penalty() @@ -1206,6 +1378,8 @@ class SpiderTableView: self._sync_buttons() def _show_forfeit_modal(self): + if self.hover_zoom is not None: + self.hover_zoom.cancel() self.engine.pause_timer() self._save_progress() penalty = self._compute_forfeit_penalty() @@ -1224,7 +1398,10 @@ class SpiderTableView: self._sync_buttons() def _handle_victory(self): + if self.hover_zoom is not None: + self.hover_zoom.cancel() self._game_concluded = True + self.engine.pause_timer() pid = self.ctx.profile["id"] Database.delete_game_state(pid, GAME_FOLDER_ID) dur = self.engine.get_elapsed_seconds() @@ -1245,9 +1422,24 @@ class SpiderTableView: duration_sec=dur, points_gained=xp_earned, ) - self.topbar.level_label.configure(text="") + self.topbar.update_level_xp_text() self.ctx.sounds.play("win") - self._show_victory_modal(xp_earned, old_lvl, new_lvl, dur) + self._sync_buttons() + + def _after_win_fx(): + self._fx_overlay = None + if not self._canvas_alive(): + return + self._show_victory_modal(xp_earned, old_lvl, new_lvl, dur) + + self._fx_overlay = EndgameFxOverlay.play( + self.ctx.root, + self.ctx.assets, + outcome="win", + on_continue=_after_win_fx, + target_canvas=self.canvas, + ) + self._sync_buttons() def _show_victory_modal(self, xp_earned: int, old_lvl: int, new_lvl: int, dur: float): lines = [ @@ -1274,6 +1466,7 @@ class SpiderTableView: self.redraw() def to_menu(): + self._close_active_modal() self._cleanup_timers() if callable(self.on_back_to_menu): self.on_back_to_menu() @@ -1282,7 +1475,6 @@ class SpiderTableView: 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), diff --git a/models/__pycache__/resource_manager.cpython-311.pyc b/models/__pycache__/resource_manager.cpython-311.pyc index e730626..1f48175 100644 Binary files a/models/__pycache__/resource_manager.cpython-311.pyc and b/models/__pycache__/resource_manager.cpython-311.pyc differ diff --git a/models/resource_manager.py b/models/resource_manager.py index fa99321..83719a5 100644 --- a/models/resource_manager.py +++ b/models/resource_manager.py @@ -14,6 +14,7 @@ class ResourceManager: self.root_dir = root_dir self.res_dir = root_dir / "resources" self.images_dir = self.res_dir / "images" + self.win_lose_dir = self.images_dir / "win_lose" self.game_icons_dir = self.images_dir / GAME_ICONS_SUBDIR self.cards_base_dir = self.images_dir / "cards" self.sounds_dir = self.res_dir / "sounds" @@ -35,6 +36,14 @@ class ResourceManager: filename = UI_IMAGES.get(key_or_filename, key_or_filename) return self.images_dir / filename + def get_win_lose_gif_path(self, filename_or_stem: str) -> Path: + name = ( + filename_or_stem + if filename_or_stem.lower().endswith(".gif") + else f"{filename_or_stem}.gif" + ) + return self.win_lose_dir / name + def get_game_icon_path(self, game_folder: str) -> Path | None: icon_file = GAME_ICON_MAP.get(game_folder) if not icon_file: diff --git a/resources/code_res/internal_base.db b/resources/code_res/internal_base.db index 6870f4f..681fad5 100644 Binary files a/resources/code_res/internal_base.db and b/resources/code_res/internal_base.db differ diff --git a/resources/code_res/sql/01_allgemein.sql b/resources/code_res/sql/01_allgemein.sql index 6175a83..73a5190 100644 --- a/resources/code_res/sql/01_allgemein.sql +++ b/resources/code_res/sql/01_allgemein.sql @@ -438,4 +438,24 @@ INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES ('stats_view_topbar', 'DE', 'Spiel-Statistiken ({0})'), ('stats_view_topbar', 'EN', 'Game Statistics ({0})'), ('xp_next_level', 'DE', '{0} / {1} XP bis Lv. {2}'), -('xp_next_level', 'EN', '{0} / {1} XP to Lv. {2}'); \ No newline at end of file +('xp_next_level', 'EN', '{0} / {1} XP to Lv. {2}'), +('settings_hover_help_desc', 'DE', 'Erklärungen beim Überfahren von Aktions-Buttons'), +('settings_hover_help_desc', 'EN', 'Display explanations when hovering action buttons'), +('settings_hover_help_title', 'DE', 'Hilfetexte bei Buttons anzeigen'), +('settings_hover_help_title', 'EN', 'Show Help Texts on Button Hover'), +('settings_lang_btn_toggle', 'DE', 'Deutsch - EN'), +('settings_lang_btn_toggle', 'EN', 'English - DE'), +('settings_lang_desc', 'DE', 'Anzeigesprache wechseln'), +('settings_lang_desc', 'EN', 'Switch display language'), +('settings_lang_title', 'DE', 'Sprache'), +('settings_lang_title', 'EN', 'Language'), +('settings_single_tap_desc', 'DE', 'Solitaire: Kurzer Klick schiebt Karten automatisch (Halten/Ziehen bleibt frei)'), +('settings_single_tap_desc', 'EN', 'Solitaire: Quick click auto-moves cards (hold & drag remain unaffected)'), +('settings_single_tap_title', 'DE', 'Einfacher Klick zum Schieben'), +('settings_single_tap_title', 'EN', 'Single tap to move'), +('settings_subtitle', 'DE', 'Sprache, Bedienhilfen & Klangkulisse'), +('settings_subtitle', 'EN', 'Language, UI Helpers & Audio'), +('settings_title', 'DE', 'Einstellungen'), +('settings_title', 'EN', 'Settings'), +('endgame_click_continue', 'DE', 'Klicken zum Fortfahren'), +('endgame_click_continue', 'EN', 'Click anywhere to continue'); \ No newline at end of file diff --git a/resources/images/cards/bavarian/B10.png b/resources/images/cards/bavarian/B10.png new file mode 100644 index 0000000..b8e9eb6 Binary files /dev/null and b/resources/images/cards/bavarian/B10.png differ diff --git a/resources/images/cards/bavarian/B6.png b/resources/images/cards/bavarian/B6.png new file mode 100644 index 0000000..ac6e42f Binary files /dev/null and b/resources/images/cards/bavarian/B6.png differ diff --git a/resources/images/cards/bavarian/B7.png b/resources/images/cards/bavarian/B7.png new file mode 100644 index 0000000..be53c41 Binary files /dev/null and b/resources/images/cards/bavarian/B7.png differ diff --git a/resources/images/cards/bavarian/B8.png b/resources/images/cards/bavarian/B8.png new file mode 100644 index 0000000..af553c5 Binary files /dev/null and b/resources/images/cards/bavarian/B8.png differ diff --git a/resources/images/cards/bavarian/B9.png b/resources/images/cards/bavarian/B9.png new file mode 100644 index 0000000..69ae58a Binary files /dev/null and b/resources/images/cards/bavarian/B9.png differ diff --git a/resources/images/cards/bavarian/BA.png b/resources/images/cards/bavarian/BA.png new file mode 100644 index 0000000..87b3e6c Binary files /dev/null and b/resources/images/cards/bavarian/BA.png differ diff --git a/resources/images/cards/bavarian/BK.png b/resources/images/cards/bavarian/BK.png new file mode 100644 index 0000000..68956dc Binary files /dev/null and b/resources/images/cards/bavarian/BK.png differ diff --git a/resources/images/cards/bavarian/BO.png b/resources/images/cards/bavarian/BO.png new file mode 100644 index 0000000..6f1807f Binary files /dev/null and b/resources/images/cards/bavarian/BO.png differ diff --git a/resources/images/cards/bavarian/BU.png b/resources/images/cards/bavarian/BU.png new file mode 100644 index 0000000..cbe3017 Binary files /dev/null and b/resources/images/cards/bavarian/BU.png differ diff --git a/resources/images/cards/bavarian/E10.png b/resources/images/cards/bavarian/E10.png new file mode 100644 index 0000000..1d1d52b Binary files /dev/null and b/resources/images/cards/bavarian/E10.png differ diff --git a/resources/images/cards/bavarian/E6.png b/resources/images/cards/bavarian/E6.png new file mode 100644 index 0000000..d87bca8 Binary files /dev/null and b/resources/images/cards/bavarian/E6.png differ diff --git a/resources/images/cards/bavarian/E7.png b/resources/images/cards/bavarian/E7.png new file mode 100644 index 0000000..440d1f7 Binary files /dev/null and b/resources/images/cards/bavarian/E7.png differ diff --git a/resources/images/cards/bavarian/E8.png b/resources/images/cards/bavarian/E8.png new file mode 100644 index 0000000..60dc7dc Binary files /dev/null and b/resources/images/cards/bavarian/E8.png differ diff --git a/resources/images/cards/bavarian/E9.png b/resources/images/cards/bavarian/E9.png new file mode 100644 index 0000000..4a69948 Binary files /dev/null and b/resources/images/cards/bavarian/E9.png differ diff --git a/resources/images/cards/bavarian/EA.png b/resources/images/cards/bavarian/EA.png new file mode 100644 index 0000000..4d14c49 Binary files /dev/null and b/resources/images/cards/bavarian/EA.png differ diff --git a/resources/images/cards/bavarian/EK.png b/resources/images/cards/bavarian/EK.png new file mode 100644 index 0000000..b0c58fd Binary files /dev/null and b/resources/images/cards/bavarian/EK.png differ diff --git a/resources/images/cards/bavarian/EO.png b/resources/images/cards/bavarian/EO.png new file mode 100644 index 0000000..cf11cec Binary files /dev/null and b/resources/images/cards/bavarian/EO.png differ diff --git a/resources/images/cards/bavarian/EU.png b/resources/images/cards/bavarian/EU.png new file mode 100644 index 0000000..f2b0226 Binary files /dev/null and b/resources/images/cards/bavarian/EU.png differ diff --git a/resources/images/cards/bavarian/H10.png b/resources/images/cards/bavarian/H10.png new file mode 100644 index 0000000..3f9f65c Binary files /dev/null and b/resources/images/cards/bavarian/H10.png differ diff --git a/resources/images/cards/bavarian/H6.png b/resources/images/cards/bavarian/H6.png new file mode 100644 index 0000000..aea868e Binary files /dev/null and b/resources/images/cards/bavarian/H6.png differ diff --git a/resources/images/cards/bavarian/H7.png b/resources/images/cards/bavarian/H7.png new file mode 100644 index 0000000..2b06cf2 Binary files /dev/null and b/resources/images/cards/bavarian/H7.png differ diff --git a/resources/images/cards/bavarian/H8.png b/resources/images/cards/bavarian/H8.png new file mode 100644 index 0000000..77fb420 Binary files /dev/null and b/resources/images/cards/bavarian/H8.png differ diff --git a/resources/images/cards/bavarian/H9.png b/resources/images/cards/bavarian/H9.png new file mode 100644 index 0000000..9c4ad57 Binary files /dev/null and b/resources/images/cards/bavarian/H9.png differ diff --git a/resources/images/cards/bavarian/HA.png b/resources/images/cards/bavarian/HA.png new file mode 100644 index 0000000..accaffc Binary files /dev/null and b/resources/images/cards/bavarian/HA.png differ diff --git a/resources/images/cards/bavarian/HK.png b/resources/images/cards/bavarian/HK.png new file mode 100644 index 0000000..c8b1f2a Binary files /dev/null and b/resources/images/cards/bavarian/HK.png differ diff --git a/resources/images/cards/bavarian/HO.png b/resources/images/cards/bavarian/HO.png new file mode 100644 index 0000000..4272668 Binary files /dev/null and b/resources/images/cards/bavarian/HO.png differ diff --git a/resources/images/cards/bavarian/HU.png b/resources/images/cards/bavarian/HU.png new file mode 100644 index 0000000..c4af9ad Binary files /dev/null and b/resources/images/cards/bavarian/HU.png differ diff --git a/resources/images/cards/bavarian/S10.png b/resources/images/cards/bavarian/S10.png new file mode 100644 index 0000000..c674167 Binary files /dev/null and b/resources/images/cards/bavarian/S10.png differ diff --git a/resources/images/cards/bavarian/S6.png b/resources/images/cards/bavarian/S6.png new file mode 100644 index 0000000..6da30ad Binary files /dev/null and b/resources/images/cards/bavarian/S6.png differ diff --git a/resources/images/cards/bavarian/S7.png b/resources/images/cards/bavarian/S7.png new file mode 100644 index 0000000..b46472a Binary files /dev/null and b/resources/images/cards/bavarian/S7.png differ diff --git a/resources/images/cards/bavarian/S8.png b/resources/images/cards/bavarian/S8.png new file mode 100644 index 0000000..1d30dc5 Binary files /dev/null and b/resources/images/cards/bavarian/S8.png differ diff --git a/resources/images/cards/bavarian/S9.png b/resources/images/cards/bavarian/S9.png new file mode 100644 index 0000000..9b5040b Binary files /dev/null and b/resources/images/cards/bavarian/S9.png differ diff --git a/resources/images/cards/bavarian/SA.png b/resources/images/cards/bavarian/SA.png new file mode 100644 index 0000000..143841d Binary files /dev/null and b/resources/images/cards/bavarian/SA.png differ diff --git a/resources/images/cards/bavarian/SK.png b/resources/images/cards/bavarian/SK.png new file mode 100644 index 0000000..2aa8c10 Binary files /dev/null and b/resources/images/cards/bavarian/SK.png differ diff --git a/resources/images/cards/bavarian/SO.png b/resources/images/cards/bavarian/SO.png new file mode 100644 index 0000000..a9a1005 Binary files /dev/null and b/resources/images/cards/bavarian/SO.png differ diff --git a/resources/images/cards/bavarian/SU.png b/resources/images/cards/bavarian/SU.png new file mode 100644 index 0000000..4293e7d Binary files /dev/null and b/resources/images/cards/bavarian/SU.png differ diff --git a/resources/images/lose.gif b/resources/images/lose.gif deleted file mode 100644 index f55ba9f..0000000 Binary files a/resources/images/lose.gif and /dev/null differ diff --git a/resources/images/win.gif b/resources/images/win.gif deleted file mode 100644 index 592a543..0000000 Binary files a/resources/images/win.gif and /dev/null differ diff --git a/resources/images/win_lose/bat_explosion.gif b/resources/images/win_lose/bat_explosion.gif new file mode 100644 index 0000000..8a293de Binary files /dev/null and b/resources/images/win_lose/bat_explosion.gif differ diff --git a/resources/images/win_lose/firework_start.gif b/resources/images/win_lose/firework_start.gif new file mode 100644 index 0000000..17e31a3 Binary files /dev/null and b/resources/images/win_lose/firework_start.gif differ diff --git a/resources/images/win_lose/foul_pumpkin.gif b/resources/images/win_lose/foul_pumpkin.gif new file mode 100644 index 0000000..8e4b197 Binary files /dev/null and b/resources/images/win_lose/foul_pumpkin.gif differ diff --git a/resources/images/win_lose/pumpkin_explosion.gif b/resources/images/win_lose/pumpkin_explosion.gif new file mode 100644 index 0000000..5627859 Binary files /dev/null and b/resources/images/win_lose/pumpkin_explosion.gif differ diff --git a/view/__pycache__/assets_manager.cpython-311.pyc b/view/__pycache__/assets_manager.cpython-311.pyc index 6cd8d91..3d5651b 100644 Binary files a/view/__pycache__/assets_manager.cpython-311.pyc and b/view/__pycache__/assets_manager.cpython-311.pyc differ diff --git a/view/assets_manager.py b/view/assets_manager.py index 0aa25a9..9966bf7 100644 --- a/view/assets_manager.py +++ b/view/assets_manager.py @@ -26,7 +26,6 @@ from resources.code_res.game_constants import ( PLAYING_CARD_SIZE, ) -# 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, @@ -35,7 +34,6 @@ BOX_SOURCE_CORNER_RATIO = { "dropdown_box": 0.085, } -# Ziel-Eckgröße im UI: (relativer_anteil_an_kleinerer_zielkante, min_px, max_px) BOX_TARGET_CORNER_SPEC = { "box_big": (0.14, 18, 46), "box_gold_small": (0.22, 14, 34), @@ -48,10 +46,6 @@ _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") @@ -85,7 +79,6 @@ class AssetManager: 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] = {} @@ -93,7 +86,6 @@ class AssetManager: 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") @@ -101,12 +93,10 @@ class AssetManager: self.raw_general_table = None self.raw_poker_table = self._load_ui_flexible("poker_table", "poker_table") - # --- 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") - # --- Transparente Zierrahmen (9-Slice, einmalig beim Start in C freigestellt) --- self.raw_boxes: dict[str, Image.Image | None] = { "box_big": _clean_box_matte_fast( self._load_ui_flexible("box_big", "box_big"), hollow_center=True @@ -126,7 +116,6 @@ class AssetManager: } self.raw_chat_frame = self.raw_boxes["box_big"] - # --- Formular-Assets (Input & geteiltes Dropdown) --- self.raw_input = self._load_ui_flexible("input_field", "input") self.raw_dropdown_closed = self._load_ui_flexible("dropdown_closed", "dropdown_closed") self.raw_dropdown_closed_btn = self._load_ui_flexible("dropdown_closed_btn", "dropdown_closed_button") @@ -139,10 +128,8 @@ class AssetManager: self.raw_dropdown_box = self.raw_boxes["dropdown_box"] self.raw_dropdown_selection = self._load_ui_flexible("dropdown_selection", "dropdown_selection") - # 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 @@ -177,10 +164,6 @@ class AssetManager: 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 @@ -188,7 +171,6 @@ class AssetManager: 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) @@ -211,7 +193,7 @@ class AssetManager: setattr(self, attr, img.resize((nw, nh), Image.Resampling.LANCZOS)) # ------------------------------------------------------------------ - # ZENTRALER HINTERGRUND-CACHE (1x Resize für Topbar, Menüs & Tische) + # ZENTRALER HINTERGRUND-CACHE & MODAL-ABDUNKLUNG # ------------------------------------------------------------------ def get_window_bg_pil(self, rw: int, rh: int) -> Image.Image | None: rw, rh = max(64, int(rw)), max(64, int(rh)) @@ -224,7 +206,6 @@ class AssetManager: 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 @@ -246,7 +227,6 @@ class AssetManager: 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]: @@ -257,6 +237,24 @@ class AssetManager: self._tk_cache[tk_key] = photo return photo + def get_dim_veil_photo( + self, width: int, height: int, alpha: int = 148 + ) -> ImageTk.PhotoImage: + """ + Erzeugt einen halbtransparenten RGBA-Abdunklungsschleier für gesperrte Spieltische, + sodass Karten und Tischdetails darunter gedimmt/ausgegraut sichtbar bleiben. + """ + w, h = max(8, int(width)), max(8, int(height)) + a = max(0, min(240, int(alpha))) + tk_key = ("dim_veil", w, h, a) + if tk_key not in self._tk_cache: + stale = [k for k in self._tk_cache if isinstance(k, tuple) and k and k[0] == "dim_veil"] + for k in stale[:-6]: + self._tk_cache.pop(k, None) + veil_pil = Image.new("RGBA", (w, h), (10, 8, 16, a)) + self._tk_cache[tk_key] = ImageTk.PhotoImage(veil_pil) + return self._tk_cache[tk_key] + # ------------------------------------------------------------------ # FONT-LOADER & OLD-LONDON TEXT-RENDERER (PIL RGBA) # ------------------------------------------------------------------ @@ -315,7 +313,6 @@ class AssetManager: 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) @@ -463,7 +460,7 @@ class AssetManager: return self._tk_cache[tk_key] # ------------------------------------------------------------------ - # 9-SLICE RAHMEN-SCALER FÜR TRANSPARENTE BOXEN (fein herunterskaliert!) + # 9-SLICE RAHMEN-SCALER FÜR TRANSPARENTE BOXEN # ------------------------------------------------------------------ def get_9slice_pil( self, @@ -497,7 +494,6 @@ class AssetManager: out = Image.new("RGBA", (tw, th), (0, 0, 0, 0)) - # 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) @@ -546,14 +542,9 @@ class AssetManager: return self._tk_cache.get(tk_key) # ------------------------------------------------------------------ - # KARTEN, BANNER & GIFS (Punkt 4: Vorgedampfter Rohkarten-Cache!) + # KARTEN, BANNER & WIN/LOSE-GIFS MIT ALPHA-KANAL # ------------------------------------------------------------------ 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) @@ -599,7 +590,7 @@ class AssetManager: def get_gif_frames(self, key_or_filename: str, size=OUTCOME_GIF_SIZE) -> list[ImageTk.PhotoImage]: cache_key = ("gif", key_or_filename, size) if cache_key not in self._tk_cache: - frames = [] + frames: list[ImageTk.PhotoImage] = [] path = self.res.get_ui_image_path(key_or_filename) if path.is_file(): try: @@ -617,15 +608,53 @@ class AssetManager: self._tk_cache[cache_key] = frames return self._tk_cache[cache_key] + def get_win_lose_gif_sequence( + self, stem_or_filename: str, size: tuple[int, int] + ) -> tuple[list[ImageTk.PhotoImage], list[int]]: + """ + Lädt transparente RGBA-GIFs aus resources/images/win_lose/ inklusive ihrer + echten Frame-Dauern (ms) und cacht sie für verzögerungsfreie Partikel-Spawns. + """ + tw, th = max(24, int(size[0])), max(24, int(size[1])) + cache_key = ("win_lose_gif", stem_or_filename, (tw, th)) + if cache_key in self._tk_cache: + return self._tk_cache[cache_key] + + raw_pil_key = ("win_lose_raw_pil", stem_or_filename) + if raw_pil_key not in self._pil_cache: + raw_frames: list[Image.Image] = [] + raw_durs: list[int] = [] + path = self.res.get_win_lose_gif_path(stem_or_filename) + if path.is_file(): + try: + with Image.open(path) as gif: + idx = 0 + while True: + dur = int(gif.info.get("duration", 65) or 65) + dur = max(35, min(200, dur)) + raw_frames.append(gif.copy().convert("RGBA")) + raw_durs.append(dur) + idx += 1 + gif.seek(idx) + except EOFError: + pass + except Exception: + pass + self._pil_cache[raw_pil_key] = (raw_frames, raw_durs) + + src_frames, src_durs = self._pil_cache[raw_pil_key] + tk_frames = [ + ImageTk.PhotoImage(fr.resize((tw, th), Image.Resampling.LANCZOS)) + for fr in src_frames + ] + result = (tk_frames, list(src_durs)) + self._tk_cache[cache_key] = result + return result + # ------------------------------------------------------------------ - # STARTUP-PRELOADER: Lädt Karten, Fonts, Boxen & Standard-Buttons vorab + # STARTUP-PRELOADER # ------------------------------------------------------------------ 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 @@ -635,19 +664,16 @@ class AssetManager: 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: @@ -662,7 +688,6 @@ class AssetManager: 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 = [ @@ -681,7 +706,6 @@ class AssetManager: 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: @@ -694,7 +718,6 @@ class AssetManager: 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 + for wl_name in ("firework_start", "bat_explosion", "pumpkin_explosion", "foul_pumpkin"): + self.get_win_lose_gif_sequence(wl_name, (170, 170)) \ No newline at end of file diff --git a/view/dialogs/__pycache__/audio_settings_dialog.cpython-311.pyc b/view/dialogs/__pycache__/audio_settings_dialog.cpython-311.pyc index 17628b9..850d9ea 100644 Binary files a/view/dialogs/__pycache__/audio_settings_dialog.cpython-311.pyc and b/view/dialogs/__pycache__/audio_settings_dialog.cpython-311.pyc differ diff --git a/view/dialogs/audio_settings_dialog.py b/view/dialogs/audio_settings_dialog.py index aaa4059..89b8ae7 100644 --- a/view/dialogs/audio_settings_dialog.py +++ b/view/dialogs/audio_settings_dialog.py @@ -5,6 +5,10 @@ from __future__ import annotations import tkinter as tk from PIL import Image, ImageTk +from games.solitaire.base.solitaire_tap_prefs import ( + is_single_tap_to_move_enabled, + set_single_tap_to_move_enabled, +) from resources.code_res.game_constants import ( BG_COLOR, FONT_COLOR_BODY_DEFAULT, @@ -35,14 +39,15 @@ def is_german_active() -> bool: class AudioSettingsDialog(tk.Canvas): """ - Rahmenloses Gothic-Einstellungs-Overlay: + Rahmenloses Gothic-Einstellungs-Overlay (768p-kompatibel): - Sprache wechseln (DE / EN) - - Animierter Switch: 'Hilfe Texte bei Buttons Anzeigen' / 'Show Help Texts on Button Hover' + - Animierter Switch: 'Hilfetexte bei Buttons anzeigen' / 'Show Help Texts on Button Hover' + - Animierter Switch: 'Einfacher Klick zum Schieben' / 'Single tap to move' - Zwei Audio-Schieberegler (Ambiance & Soundeffekte) """ DLG_W = 500 - DLG_H = 604 + DLG_H = 656 @classmethod def open( @@ -114,7 +119,6 @@ class AudioSettingsDialog(tk.Canvas): self._sliders.clear() w, h = self.DLG_W, self.DLG_H - is_de = is_german_active() # 1. Hochformat-Hintergrund + box_big.png Zierrahmen bg_src = self.assets.raw_bg_vertical or self.assets.raw_bg_horizontal or self.assets.raw_bg @@ -130,39 +134,45 @@ class AudioSettingsDialog(tk.Canvas): self.create_image(w // 2, h // 2, image=outer_box, anchor="center") # 2. Titel & Untertitel - dlg_title = "Einstellungen" if is_de else "Settings" - dlg_sub = ( - "Sprache, Bedienhilfen & Klangkulisse" - if is_de - else "Language, UI Helpers & Audio" - ) - title_ph = self.assets.get_goth_text_photo( - dlg_title, + t("settings_title"), size_px=FONT_SIZE_TITLE_LG - 2, color=FONT_COLOR_TITLE_MAIN, max_width=w - 60, ) sub_ph = self.assets.get_goth_text_photo( - dlg_sub, + t("settings_subtitle"), size_px=FONT_SIZE_SMALL_MIN, color=FONT_COLOR_BODY_MUTED, max_width=w - 70, ) self._photo_refs.extend([title_ph, sub_ph]) - self.create_image(w // 2, 40, image=title_ph, anchor="center") - self.create_image(w // 2, 70, image=sub_ph, anchor="center") + self.create_image(w // 2, 36, image=title_ph, anchor="center") + self.create_image(w // 2, 64, image=sub_ph, anchor="center") # 3. Sprach-Box - self._create_language_box(cy=128, is_de=is_de) + self._create_language_box(cy=118) - # 4. Hover-Hilfetext-Switch-Box (mit animiertem GothSwitch) - self._create_hover_help_switch_box(cy=214, is_de=is_de) + # 4. Zwei Bedienhilfe-Switches (Hover-Hilfetexte & Einfacher Klick zum Schieben) + self._create_switch_box( + cy=196, + title_txt=t("settings_hover_help_title"), + desc_txt=t("settings_hover_help_desc"), + initial_state=is_button_hover_help_enabled(), + on_toggle=lambda state: set_button_hover_help_enabled(state, persist=True), + ) + self._create_switch_box( + cy=274, + title_txt=t("settings_single_tap_title"), + desc_txt=t("settings_single_tap_desc"), + initial_state=is_single_tap_to_move_enabled(), + on_toggle=lambda state: set_single_tap_to_move_enabled(state, persist=True), + ) # 5. Zwei Audio-Slider-Boxen self._create_goth_slider( key="amb", - cy=320, + cy=372, label_txt=t("audio_ambiance_label"), desc_txt=t("audio_ambiance_desc"), initial_vol=self.sound_mgr.ambiance_volume, @@ -170,7 +180,7 @@ class AudioSettingsDialog(tk.Canvas): ) self._create_goth_slider( key="sfx", - cy=438, + cy=482, label_txt=t("audio_sfx_label"), desc_txt=t("audio_sfx_desc"), initial_vol=self.sound_mgr.menu_volume, @@ -204,15 +214,15 @@ class AudioSettingsDialog(tk.Canvas): height=40, style="fire", ) - self.create_window(42, h - 46, window=btn_test, anchor="w") - self.create_window(w - 42, h - 46, window=btn_done, anchor="e") + self.create_window(42, h - 44, window=btn_test, anchor="w") + self.create_window(w - 42, h - 44, window=btn_done, anchor="e") self.bind("", self._on_mouse_down) self.bind("", self._on_mouse_drag) self.bind("", lambda _e: setattr(self, "_dragging_key", None)) - def _create_language_box(self, cy: int, is_de: bool): - box_w, box_h = self.DLG_W - 72, 74 + def _create_language_box(self, cy: int): + box_w, box_h = self.DLG_W - 72, 68 cx = self.DLG_W // 2 x_left = cx - box_w // 2 + 22 x_right = cx + box_w // 2 - 20 @@ -222,33 +232,29 @@ class AudioSettingsDialog(tk.Canvas): self._photo_refs.append(sec_box) self.create_image(cx, cy, image=sec_box, anchor="center") - lang_heading = "Sprache" if is_de else "Language" - lang_desc = "Anzeigesprache wechseln" if is_de else "Switch display language" - lbl_ph = self.assets.get_goth_text_photo( - lang_heading, + t("settings_lang_title"), size_px=FONT_SIZE_HEADING - 4, color=FONT_COLOR_BODY_DEFAULT, align="left", ) desc_ph = self.assets.get_goth_text_photo( - lang_desc, + t("settings_lang_desc"), size_px=FONT_SIZE_SMALL_MIN, color=FONT_COLOR_BODY_MUTED, max_width=box_w - 180, align="left", ) self._photo_refs.extend([lbl_ph, desc_ph]) - self.create_image(x_left, cy - 12, image=lbl_ph, anchor="w") - self.create_image(x_left, cy + 13, image=desc_ph, anchor="w") + self.create_image(x_left, cy - 11, image=lbl_ph, anchor="w") + self.create_image(x_left, cy + 12, image=desc_ph, anchor="w") btn_norm = self.assets.raw_btn_default btn_purp = self.assets.raw_btn_purple - lang_btn_txt = "Deutsch - EN" if is_de else "English - DE" btn_lang = ImageButton( self, - lang_btn_txt, + t("settings_lang_btn_toggle"), btn_norm, btn_purp, self._handle_language_toggle, @@ -260,8 +266,15 @@ class AudioSettingsDialog(tk.Canvas): ) self.create_window(x_right, cy, window=btn_lang, anchor="e") - def _create_hover_help_switch_box(self, cy: int, is_de: bool): - box_w, box_h = self.DLG_W - 72, 76 + def _create_switch_box( + self, + cy: int, + title_txt: str, + desc_txt: str, + initial_state: bool, + on_toggle, + ): + box_w, box_h = self.DLG_W - 72, 70 cx = self.DLG_W // 2 x_left = cx - box_w // 2 + 22 x_right = cx + box_w // 2 - 20 @@ -271,36 +284,25 @@ class AudioSettingsDialog(tk.Canvas): self._photo_refs.append(sec_box) self.create_image(cx, cy, image=sec_box, anchor="center") - sw_title = ( - "Hilfe Texte bei Buttons Anzeigen" - if is_de - else "Show Help Texts on Button Hover" - ) - sw_desc = ( - "Erklärungen beim Überfahren von Aktions-Buttons" - if is_de - else "Display explanations when hovering action buttons" - ) - lbl_ph = self.assets.get_goth_text_photo( - sw_title, + title_txt, size_px=FONT_SIZE_BODY + 1, color=FONT_COLOR_BODY_DEFAULT, max_width=box_w - 144, align="left", ) desc_ph = self.assets.get_goth_text_photo( - sw_desc, + desc_txt, size_px=FONT_SIZE_SMALL_MIN, color=FONT_COLOR_BODY_MUTED, max_width=box_w - 144, align="left", ) self._photo_refs.extend([lbl_ph, desc_ph]) - self.create_image(x_left, cy - 12, image=lbl_ph, anchor="w") - self.create_image(x_left, cy + 14, image=desc_ph, anchor="w") + self.create_image(x_left, cy - 11, image=lbl_ph, anchor="w") + self.create_image(x_left, cy + 13, image=desc_ph, anchor="w") - sw_w, sw_h = 92, 40 + sw_w, sw_h = 92, 38 sw_cx = x_right - sw_w // 2 patch_ph = self._crop_dialog_bg_patch(sw_cx, cy, sw_w, sw_h) if patch_ph is not None: @@ -308,8 +310,8 @@ class AudioSettingsDialog(tk.Canvas): switch_wgt = GothSwitch( self, - value=is_button_hover_help_enabled(), - on_change=lambda state: set_button_hover_help_enabled(state, persist=True), + value=initial_state, + on_change=on_toggle, sound_mgr=self.sound_mgr, width=sw_w, height=sw_h, @@ -345,7 +347,7 @@ class AudioSettingsDialog(tk.Canvas): initial_vol: float, on_change, ): - box_w, box_h = self.DLG_W - 72, 104 + box_w, box_h = self.DLG_W - 72, 98 cx = self.DLG_W // 2 x_left = cx - box_w // 2 + 22 x_right = cx + box_w // 2 - 22 @@ -369,12 +371,12 @@ class AudioSettingsDialog(tk.Canvas): align="left", ) self._photo_refs.extend([lbl_ph, desc_ph]) - self.create_image(x_left, cy - 28, image=lbl_ph, anchor="w") - self.create_image(x_left, cy - 4, image=desc_ph, anchor="w") + self.create_image(x_left, cy - 26, image=lbl_ph, anchor="w") + self.create_image(x_left, cy - 3, image=desc_ph, anchor="w") - pct_item = self.create_image(x_right, cy - 28, anchor="e") + pct_item = self.create_image(x_right, cy - 26, anchor="e") - track_y = cy + 26 + track_y = cy + 24 track_x1 = x_left + 4 track_x2 = x_right - 4 self.create_rectangle( diff --git a/view/widgets/endgame_fx_overlay.py b/view/widgets/endgame_fx_overlay.py new file mode 100644 index 0000000..76eac12 --- /dev/null +++ b/view/widgets/endgame_fx_overlay.py @@ -0,0 +1,381 @@ +# -*- coding: utf-8 -*- +# view/widgets/endgame_fx_overlay.py +from __future__ import annotations + +import random +import time +import tkinter as tk +from collections import deque + +from resources.code_res.game_constants import ( + FONT_COLOR_TITLE_MAIN, + FONT_SIZE_SMALL_MIN, +) +from resources.code_res.i18n import t +from view.widgets.modal_veil import ModalVeil + + +class EndgameFxOverlay: + """ + Vorschalt-Animation bei Spielende über dem gesperrten, abgedunkelten Spieltisch: + - Sieg ('win'): 'firework_start.gif' unten links + zufällig über den Bildschirm + verteilte 'bat_explosion.gif' & 'pumpkin_explosion.gif' an wechselnden Punkten. + - Niederlage ('lose'): 'foul_pumpkin.gif' zufällig über den Bildschirm verteilt. + - Erst nach einem Klick (oder Space/Enter/Esc) geht es weiter zum Ergebnis-Screen. + """ + + GRACE_SEC = 0.20 + FX_TAG = "endgame_fx_item" + HINT_TAG = "endgame_fx_hint" + _SEQ = 0 + + @classmethod + def play( + cls, + root: tk.Misc, + assets, + outcome: str | bool | None, + on_continue, + target_canvas: tk.Canvas | None = None, + ) -> "EndgameFxOverlay | None": + if outcome is True: + mode = "win" + elif outcome is False: + mode = "lose" + elif isinstance(outcome, str) and outcome.lower() in ("win", "lose"): + mode = outcome.lower() + else: + on_continue() + return None + + return cls(root, assets, mode, on_continue, target_canvas=target_canvas) + + def __init__( + self, + root: tk.Misc, + assets, + mode: str, + on_continue, + target_canvas: tk.Canvas | None = None, + ): + EndgameFxOverlay._SEQ += 1 + self._id = EndgameFxOverlay._SEQ + self.root = root.winfo_toplevel() + self.assets = assets + self.mode = mode + self.on_continue = on_continue + + self._finished = False + self._armed_press = False + self._start_ts = time.monotonic() + self._jobs: set[str] = set() + self._active_spots: dict[int, tuple[int, int, int]] = {} + self._recent_spots: deque[tuple[int, int]] = deque(maxlen=5) + self._photo_refs: list = [] + + self._click_tag = f"EndgameClickTag_{self._id}" + self._tagged_widgets: list[tk.Misc] = [] + + self._veil = ModalVeil( + self.root, + self.assets, + modal_widget=None, + target_canvas=target_canvas, + dim_alpha=136, + ) + self.canvas = self._veil.canvas + + if self.canvas is None or not self._has_any_frames(): + self._veil.release() + self.on_continue() + return + + self._install_click_catcher() + self._draw_continue_banner() + self._start_choreography() + + def _has_any_frames(self) -> bool: + probe_name = "firework_start" if self.mode == "win" else "foul_pumpkin" + frames, _ = self.assets.get_win_lose_gif_sequence(probe_name, (160, 160)) + return bool(frames) + + def _schedule(self, delay_ms: int, fn, *args) -> str | None: + if self._finished: + return None + job_holder: list[str] = [] + + def _wrapped(): + if job_holder: + self._jobs.discard(job_holder[0]) + if not self._finished and self._canvas_ok(): + fn(*args) + + try: + jid = self.root.after(max(1, int(delay_ms)), _wrapped) + job_holder.append(jid) + self._jobs.add(jid) + return jid + except Exception: + return None + + def _canvas_ok(self) -> bool: + try: + return bool(self.canvas is not None and self.canvas.winfo_exists()) + except Exception: + return False + + # ------------------------------------------------------------------ + # KLICK-FÄNGER ÜBER DEM GESAMTEN FENSTER + # ------------------------------------------------------------------ + def _install_click_catcher(self): + for seq in ("", "", "", "", ""): + self.root.bind_class(self._click_tag, seq, lambda _e: "break") + self.root.bind_class(self._click_tag, "", self._on_press) + self.root.bind_class(self._click_tag, "", self._on_release) + self.root.bind_class(self._click_tag, "", self._on_press) + self.root.bind_class(self._click_tag, "", self._on_release) + self.root.bind_class(self._click_tag, "", self._on_key) + + self._tag_tree(self.root) + + def _tag_tree(self, node: tk.Misc): + try: + tags = list(node.bindtags()) + if self._click_tag not in tags: + node.bindtags((self._click_tag, *tags)) + self._tagged_widgets.append(node) + for child in node.winfo_children(): + self._tag_tree(child) + except tk.TclError: + pass + + def _on_press(self, _event=None): + if (time.monotonic() - self._start_ts) >= self.GRACE_SEC: + self._armed_press = True + return "break" + + def _on_release(self, _event=None): + if self._armed_press and (time.monotonic() - self._start_ts) >= self.GRACE_SEC: + self.finish() + return "break" + + def _on_key(self, event): + if (time.monotonic() - self._start_ts) >= self.GRACE_SEC: + if event.keysym in ("space", "Return", "KP_Enter", "Escape"): + self.finish() + return "break" + + # ------------------------------------------------------------------ + # HINWEIS-BANNER ("Klicken zum Fortfahren") + # ------------------------------------------------------------------ + def _draw_continue_banner(self): + if not self._canvas_ok(): + return + cw = max(320, self.canvas.winfo_width()) + ch = max(240, self.canvas.winfo_height()) + + txt_ph = self.assets.get_goth_text_photo( + t("endgame_click_continue"), + FONT_SIZE_SMALL_MIN + 2, + FONT_COLOR_TITLE_MAIN, + ) + bw = txt_ph.width() + 54 + bh = max(38, txt_ph.height() + 14) + box_ph = self.assets.get_box_photo("box_purple", (bw, bh)) + self._photo_refs.extend([txt_ph, box_ph] if box_ph else [txt_ph]) + + cx = cw // 2 + cy = ch - bh // 2 - 14 + if box_ph: + self.canvas.create_image(cx, cy, image=box_ph, anchor="center", tags=(self.FX_TAG, self.HINT_TAG)) + self.canvas.create_image(cx, cy, image=txt_ph, anchor="center", tags=(self.FX_TAG, self.HINT_TAG)) + + # ------------------------------------------------------------------ + # WIN / LOSE PARTIKEL-CHOREOGRAFIE + # ------------------------------------------------------------------ + def _start_choreography(self): + if self.mode == "win": + self._launch_firework_bottom_left() + self._schedule(260, self._win_explosion_wave, True) + else: + self._schedule(50, self._lose_pumpkin_wave, True) + + def _launch_firework_bottom_left(self): + if self._finished or not self._canvas_ok(): + return + cw = max(320, self.canvas.winfo_width()) + ch = max(240, self.canvas.winfo_height()) + fw_sz = max(175, min(285, int(min(cw, ch) * 0.38))) + frames, durs = self.assets.get_win_lose_gif_sequence("firework_start", (fw_sz, fw_sz)) + if not frames: + return + + item_id = self.canvas.create_image( + 14, ch, + image=frames[0], + anchor="sw", + tags=(self.FX_TAG,), + ) + self.canvas.tag_raise(self.HINT_TAG) + + def _step_fw(idx: int): + if self._finished or not self._canvas_ok(): + return + if idx >= len(frames): + try: + self.canvas.delete(item_id) + except Exception: + pass + # Neue Salve nach kurzer Feuerpause starten + self._schedule(780, self._launch_firework_bottom_left) + return + self.canvas.itemconfigure(item_id, image=frames[idx]) + self._schedule(durs[idx], _step_fw, idx + 1) + + self._schedule(durs[0], _step_fw, 1) + + def _pick_random_spot(self, size_px: int, avoid_bottom_left: bool) -> tuple[int, int]: + cw = max(360, self.canvas.winfo_width()) + ch = max(260, self.canvas.winfo_height()) + half = size_px // 2 + x_min = half + 18 + x_max = max(x_min + 20, cw - half - 18) + y_min = half + 14 + y_max = max(y_min + 20, ch - half - 64) + + best_xy = (random.randint(x_min, x_max), random.randint(y_min, y_max)) + min_dist_sq = int((size_px * 0.78) ** 2) + + for _ in range(18): + rx = random.randint(x_min, x_max) + ry = random.randint(y_min, y_max) + + # Unten links Platz für die Raketen-Abschussrampe lassen + if avoid_bottom_left and rx < int(cw * 0.28) and ry > int(ch * 0.56): + continue + + too_close = False + for ax, ay, _asz in self._active_spots.values(): + if (rx - ax) ** 2 + (ry - ay) ** 2 < min_dist_sq: + too_close = True + break + if not too_close: + for px, py in self._recent_spots: + if (rx - px) ** 2 + (ry - py) ** 2 < int(min_dist_sq * 0.65): + too_close = True + break + + if not too_close: + best_xy = (rx, ry) + break + + self._recent_spots.append(best_xy) + return best_xy + + def _spawn_one_shot_sprite(self, gif_name: str, scale_factor: float, avoid_bottom_left: bool): + if self._finished or not self._canvas_ok(): + return + cw = max(360, self.canvas.winfo_width()) + ch = max(260, self.canvas.winfo_height()) + sz = max(125, min(250, int(min(cw, ch) * scale_factor))) + frames, durs = self.assets.get_win_lose_gif_sequence(gif_name, (sz, sz)) + if not frames: + return + + sx, sy = self._pick_random_spot(sz, avoid_bottom_left=avoid_bottom_left) + item_id = self.canvas.create_image( + sx, sy, + image=frames[0], + anchor="center", + tags=(self.FX_TAG,), + ) + self._active_spots[item_id] = (sx, sy, sz) + self.canvas.tag_raise(self.HINT_TAG) + + def _step_sprite(idx: int): + if self._finished or not self._canvas_ok(): + return + if idx >= len(frames): + self._active_spots.pop(item_id, None) + try: + self.canvas.delete(item_id) + except Exception: + pass + return + self.canvas.itemconfigure(item_id, image=frames[idx]) + self._schedule(durs[idx], _step_sprite, idx + 1) + + self._schedule(durs[0], _step_sprite, 1) + + def _win_explosion_wave(self, initial_burst: bool = False): + if self._finished or not self._canvas_ok(): + return + scales = (0.24, 0.29, 0.34) + if initial_burst: + for extra_delay in (0, 140): + chosen = random.choice(("bat_explosion", "pumpkin_explosion")) + sc = random.choice(scales) + if extra_delay == 0: + self._spawn_one_shot_sprite(chosen, sc, avoid_bottom_left=True) + else: + self._schedule(extra_delay, self._spawn_one_shot_sprite, chosen, sc, True) + elif len(self._active_spots) < 4: + chosen = random.choice(("bat_explosion", "pumpkin_explosion")) + self._spawn_one_shot_sprite(chosen, random.choice(scales), avoid_bottom_left=True) + + self._schedule(random.randint(250, 420), self._win_explosion_wave, False) + + def _lose_pumpkin_wave(self, initial_burst: bool = False): + if self._finished or not self._canvas_ok(): + return + scales = (0.23, 0.28, 0.33) + if initial_burst: + self._spawn_one_shot_sprite("foul_pumpkin", 0.29, avoid_bottom_left=False) + self._schedule(190, self._spawn_one_shot_sprite, "foul_pumpkin", 0.24, False) + elif len(self._active_spots) < 3: + self._spawn_one_shot_sprite("foul_pumpkin", random.choice(scales), avoid_bottom_left=False) + + self._schedule(random.randint(330, 510), self._lose_pumpkin_wave, False) + + # ------------------------------------------------------------------ + # SAUBERES AUFRÄUMEN & ÜBERGANG ZUM RESULT-SCREEN + # ------------------------------------------------------------------ + def cancel(self): + self._cleanup_only() + + def _cleanup_only(self): + if self._finished: + return + self._finished = True + + for jid in list(self._jobs): + try: + self.root.after_cancel(jid) + except Exception: + pass + self._jobs.clear() + self._active_spots.clear() + self._photo_refs.clear() + + if self._canvas_ok(): + try: + self.canvas.delete(self.FX_TAG) + except Exception: + pass + + for w in self._tagged_widgets: + try: + if w.winfo_exists(): + tags = [tg for tg in w.bindtags() if tg != self._click_tag] + w.bindtags(tuple(tags)) + except Exception: + pass + self._tagged_widgets.clear() + self._veil.release() + + def finish(self): + if self._finished: + return + self._cleanup_only() + if callable(self.on_continue): + self.on_continue() \ No newline at end of file diff --git a/view/widgets/modal_veil.py b/view/widgets/modal_veil.py new file mode 100644 index 0000000..dc5ceeb --- /dev/null +++ b/view/widgets/modal_veil.py @@ -0,0 +1,218 @@ +# -*- coding: utf-8 -*- +# view/widgets/modal_veil.py +from __future__ import annotations + +import tkinter as tk + + +class ModalVeil: + """ + Universeller Modal-Blocker & Abdunklungs-Schleier: + - Legt einen halbtransparenten RGBA-Schleier über das aktive Spielfeld-Canvas, + sodass Karten/Chips darunter ausgegraut sichtbar bleiben. + - Hebt das übergebene Modal-Fenster über alle UI-Leisten (Topbar, Bottom-Bar, Tisch). + - Blockiert sämtliche Klicks, Hover-Events und Tastenkürzel außerhalb des Modals. + """ + + _SEQ_COUNTER = 0 + + def __init__( + self, + root: tk.Misc, + assets, + modal_widget: tk.Widget | None = None, + target_canvas: tk.Canvas | None = None, + dim_alpha: int = 148, + ): + ModalVeil._SEQ_COUNTER += 1 + self._id = ModalVeil._SEQ_COUNTER + self.root = root.winfo_toplevel() + self.assets = assets + self.modal_widget = modal_widget + self.dim_alpha = dim_alpha + self._veil_tag = f"modal_dim_veil_{self._id}" + self._block_tag = f"ModalBlockTag_{self._id}" + self._released = False + self._tagged_widgets: list[tk.Misc] = [] + self._cfg_bind_id: str | None = None + self._resize_job: str | None = None + + self.canvas = target_canvas or self._find_play_canvas() + self._draw_veil() + self._install_input_lock() + + if self.modal_widget is not None: + tk.Widget.tkraise(self.modal_widget) + self.modal_widget.bind("", self._on_modal_destroy, add="+") + + try: + self._cfg_bind_id = self.root.bind("", self._on_root_configure, add="+") + except tk.TclError: + self._cfg_bind_id = None + + def _find_play_canvas(self) -> tk.Canvas | None: + best: tk.Canvas | None = None + best_area = 0 + candidates = list(self.root.winfo_children()) + for child in list(candidates): + if isinstance(child, tk.Frame): + candidates.extend(child.winfo_children()) + + for w in candidates: + if w is self.modal_widget or not isinstance(w, tk.Canvas): + continue + try: + if not w.winfo_ismapped(): + continue + cw, ch = w.winfo_width(), w.winfo_height() + except tk.TclError: + continue + if ch < 150: + continue + area = cw * ch + if area > best_area: + best_area = area + best = w + return best + + def _is_inside_modal(self, widget: tk.Misc | None) -> bool: + if self.modal_widget is None or widget is None: + return False + cur: tk.Misc | None = widget + while cur is not None: + if cur is self.modal_widget: + return True + cur = getattr(cur, "master", None) + return False + + def _consume_event(self, event): + if self._is_inside_modal(getattr(event, "widget", None)): + return None + return "break" + + def _install_input_lock(self): + blocked_seqs = ( + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + ) + for seq in blocked_seqs: + try: + self.root.bind_class(self._block_tag, seq, self._consume_event) + except tk.TclError: + pass + + self._apply_block_tag_recursive(self.root) + + def _apply_block_tag_recursive(self, node: tk.Misc): + if node is self.modal_widget: + return + try: + tags = list(node.bindtags()) + if self._block_tag not in tags: + node.bindtags((self._block_tag, *tags)) + self._tagged_widgets.append(node) + for child in node.winfo_children(): + self._apply_block_tag_recursive(child) + except tk.TclError: + pass + + def _draw_veil(self): + if self._released or self.canvas is None or self.assets is None: + return + try: + if not self.canvas.winfo_exists(): + return + cw = max(64, self.canvas.winfo_width()) + ch = max(64, self.canvas.winfo_height()) + self.canvas.delete(self._veil_tag) + veil_ph = self.assets.get_dim_veil_photo(cw, ch, alpha=self.dim_alpha) + self.canvas.create_image( + 0, 0, + image=veil_ph, + anchor="nw", + tags=("modal_dim_veil", self._veil_tag), + ) + self.canvas.tag_raise(self._veil_tag) + except tk.TclError: + pass + + def _on_root_configure(self, _event=None): + if self._released: + return + if self.modal_widget is not None: + try: + if self.modal_widget.winfo_exists(): + tk.Widget.tkraise(self.modal_widget) + except tk.TclError: + pass + if self._resize_job is not None: + try: + self.root.after_cancel(self._resize_job) + except Exception: + pass + try: + self._resize_job = self.root.after(60, self._refresh_after_resize) + except Exception: + self._resize_job = None + + def _refresh_after_resize(self): + self._resize_job = None + if self._released: + return + self._draw_veil() + self._apply_block_tag_recursive(self.root) + if self.modal_widget is not None: + try: + if self.modal_widget.winfo_exists(): + tk.Widget.tkraise(self.modal_widget) + except tk.TclError: + pass + + def _on_modal_destroy(self, event=None): + if event is not None and event.widget is not self.modal_widget: + return + self.release() + + def release(self): + if self._released: + return + self._released = True + + if self._resize_job is not None: + try: + self.root.after_cancel(self._resize_job) + except Exception: + pass + self._resize_job = None + + if self._cfg_bind_id is not None: + try: + self.root.unbind("", self._cfg_bind_id) + except Exception: + pass + self._cfg_bind_id = None + + if self.canvas is not None: + try: + if self.canvas.winfo_exists(): + self.canvas.delete(self._veil_tag) + except Exception: + pass + + for w in self._tagged_widgets: + try: + if w.winfo_exists(): + tags = [t for t in w.bindtags() if t != self._block_tag] + w.bindtags(tuple(tags)) + except Exception: + pass + self._tagged_widgets.clear() \ No newline at end of file