# -*- coding: utf-8 -*- # games/solitaire/base/card_animator.py from __future__ import annotations import random import time import tkinter as tk from typing import Callable, Iterable from PIL import Image, ImageTk class CardFlightAnimator: """ Zentraler, nicht-blockierender Canvas-Animator für alle Solitaire-Tische: 1. Gleitende Kartenflüge zwischen Stapeln (start / flush) 2. Rotierend nach unten aus dem Fenster fallende Karten (spawn_falling_cards) 3. Kurzes horizontales Fehler-Wackeln bei ungültigen Kombis (start_shake) """ FRAME_MS = 14 FALL_STEP_MS = 16 SHAKE_OFFSETS_PX: tuple[int, ...] = (-7, 7, -5, 5, -3, 3, 0) SHAKE_STEP_MS = 26 def __init__(self, root: tk.Misc, canvas: tk.Canvas): self.root = root self.canvas = canvas # 1. Lineare Kartenflüge self._job: str | None = None self._flights: list[dict] = [] self._on_done: Callable[[], None] | None = None self._start_ts: float = 0.0 self._duration_sec: float = 0.12 # 2. Rotierend herausfallende Karten self._fall_job: str | None = None self._falling_cards: list[dict] = [] self._fall_photo_refs: list[ImageTk.PhotoImage] = [] # 3. Horizontales Fehler-Wackeln self._shake_job: str | None = None self._shake_refs: set[tuple] = set() self._shake_dx: int = 0 @property def is_active(self) -> bool: return self._job is not None @property def has_shake(self) -> bool: return bool(self._shake_refs) def _canvas_alive(self) -> bool: try: return bool(self.canvas.winfo_exists()) except Exception: return False def cancel(self): """Bricht alle laufenden Flug-, Fall- und Wackel-Timer sofort sauber ab.""" if self._job is not None: try: self.root.after_cancel(self._job) except Exception: pass self._job = None if self._canvas_alive_safe(): self.canvas.delete("anim_flight") self._flights.clear() self._on_done = None self.cancel_falling() self.cancel_shake() def _canvas_alive_safe(self) -> bool: try: return bool(self.canvas.winfo_exists()) except Exception: return False def flush(self): """Beendet eine laufende Flug-Animation sofort sauber im Zielzustand.""" if not self.is_active: return cb = self._on_done if self._job is not None: try: self.root.after_cancel(self._job) except Exception: pass self._job = None if self._canvas_alive_safe(): self.canvas.delete("anim_flight") self._flights.clear() self._on_done = None if callable(cb): cb() # ------------------------------------------------------------------ # 1. Lineare Kartenflüge (Tableau / Foundation / Talon -> Waste) # ------------------------------------------------------------------ def start( self, flights: list[dict], draw_card_cb: Callable, duration_ms: int = 115, on_done: Callable[[], None] | None = None, ): self.flush() if not flights or not self._canvas_alive(): if callable(on_done): on_done() return active_flights: list[dict] = [] max_dist = 0.0 for idx, item in enumerate(flights): sx, sy = item["start"] ex, ey = item["end"] dist = ((ex - sx) ** 2 + (ey - sy) ** 2) ** 0.5 if dist > max_dist: max_dist = dist tag = f"anim_item_{idx}" draw_card_cb( item["card"], int(round(sx)), int(round(sy)), tags=("anim_flight", tag), highlight_color=item.get("highlight"), ) active_flights.append({ "tag": tag, "sx": float(sx), "sy": float(sy), "ex": float(ex), "ey": float(ey), "cur_x": float(sx), "cur_y": float(sy), }) if max_dist < 4.0: self.canvas.delete("anim_flight") if callable(on_done): on_done() return scaled_ms = max( 65, min(165, int(duration_ms * (0.72 + min(1.0, max_dist / 520.0) * 0.45))) ) self._flights = active_flights self._on_done = on_done self._duration_sec = scaled_ms / 1000.0 self._start_ts = time.perf_counter() self._step() def _step(self): self._job = None if not self._canvas_alive(): self._flights.clear() self._on_done = None return elapsed = time.perf_counter() - self._start_ts t_raw = min(1.0, max(0.0, elapsed / max(0.001, self._duration_sec))) ease = 1.0 - ((1.0 - t_raw) ** 3) for fl in self._flights: nx = fl["sx"] + (fl["ex"] - fl["sx"]) * ease ny = fl["sy"] + (fl["ey"] - fl["sy"]) * ease dx = nx - fl["cur_x"] dy = ny - fl["cur_y"] if abs(dx) >= 0.25 or abs(dy) >= 0.25: self.canvas.move(fl["tag"], dx, dy) fl["cur_x"] = nx fl["cur_y"] = ny if t_raw >= 1.0: cb = self._on_done self._flights.clear() self._on_done = None try: self.canvas.delete("anim_flight") except Exception: pass if callable(cb): cb() return try: self._job = self.root.after(self.FRAME_MS, self._step) except Exception: self._job = None # ------------------------------------------------------------------ # 2. Drehendes Herausfallen abgeräumter Karten (Pyramid / Effects) # ------------------------------------------------------------------ def cancel_falling(self): if self._fall_job is not None: try: self.root.after_cancel(self._fall_job) except Exception: pass self._fall_job = None self._falling_cards.clear() self._fall_photo_refs.clear() if self._canvas_alive(): self.canvas.delete("falling_fx") @staticmethod def _load_scaled_card_pil(assets, card, card_size: tuple[int, int]) -> Image.Image | None: card_path = assets.res.get_card_path(card.filename) raw_pil = None if hasattr(assets, "_get_raw_card_pil"): raw_pil = assets._get_raw_card_pil(card_path) elif card_path.is_file(): try: with Image.open(card_path) as im: raw_pil = im.convert("RGBA") except Exception: raw_pil = None if raw_pil is None: return None return raw_pil.convert("RGBA").resize(card_size, Image.Resampling.BILINEAR) def spawn_falling_cards( self, assets, card_size: tuple[int, int], items: list[tuple[object, tuple[int, int]]], ): """Lässt abgeräumte Karten leicht hochhüpfen und sich drehend nach unten herausfallen.""" if not self._canvas_alive() or not items: return cw, ch = card_size n = len(items) for idx, (card, (sx, sy)) in enumerate(items): base_pil = self._load_scaled_card_pil(assets, card, card_size) if base_pil is None: continue dir_sign = (-1 if idx == 0 else 1) if n >= 2 else random.choice((-1, 1)) self._falling_cards.append({ "pil": base_pil, "cx": float(sx + cw // 2), "cy": float(sy + ch // 2), "vx": dir_sign * random.uniform(1.8, 4.2), "vy": random.uniform(-6.4, -3.8), "angle": 0.0, "ang_vel": dir_sign * random.uniform(7.5, 13.5), }) if self._falling_cards and self._fall_job is None: self._step_falling() def redraw_falling_layer(self): if not self._falling_cards or not self._canvas_alive(): return self.canvas.delete("falling_fx") self._fall_photo_refs.clear() for p in self._falling_cards: rot_pil = p["pil"].rotate( p["angle"], resample=Image.Resampling.BILINEAR, expand=True ) tk_ph = ImageTk.PhotoImage(rot_pil) self._fall_photo_refs.append(tk_ph) self.canvas.create_image( int(round(p["cx"])), int(round(p["cy"])), image=tk_ph, anchor="center", tags=("falling_fx",), ) if self.canvas.find_withtag("modal_dim_veil"): self.canvas.tag_lower("falling_fx", "modal_dim_veil") def _step_falling(self): self._fall_job = None if not self._canvas_alive(): self._falling_cards.clear() self._fall_photo_refs.clear() return limit_y = max(600, self.canvas.winfo_height()) + 240 survivors: list[dict] = [] for p in self._falling_cards: p["cx"] += p["vx"] p["cy"] += p["vy"] p["vy"] += 1.20 p["angle"] = (p["angle"] + p["ang_vel"]) % 360.0 if p["cy"] < limit_y: survivors.append(p) self._falling_cards = survivors if not self._falling_cards: self._fall_photo_refs.clear() self.canvas.delete("falling_fx") return self.redraw_falling_layer() try: self._fall_job = self.root.after(self.FALL_STEP_MS, self._step_falling) except Exception: self._fall_job = None # ------------------------------------------------------------------ # 3. Horizontales Fehler-Wackeln (Pyramid & TriPeaks) # ------------------------------------------------------------------ def cancel_shake(self, on_clear: Callable[[], None] | None = None): was_shaking = bool(self._shake_refs) or (self._shake_job is not None) if self._shake_job is not None: try: self.root.after_cancel(self._shake_job) except Exception: pass self._shake_job = None self._shake_refs.clear() self._shake_dx = 0 if was_shaking and callable(on_clear) and self._canvas_alive(): on_clear() def shake_state_for(self, ref: tuple) -> tuple[bool, int]: if ref in self._shake_refs: return True, self._shake_dx return False, 0 def start_shake(self, refs: Iterable[tuple], redraw_cb: Callable[[], None]): self.cancel_shake() self._shake_refs = {r for r in refs if r is not None} if not self._shake_refs or not self._canvas_alive(): return def _step_shake(idx: int): self._shake_job = None if not self._canvas_alive(): self._shake_refs.clear() self._shake_dx = 0 return if idx >= len(self.SHAKE_OFFSETS_PX): self._shake_refs.clear() self._shake_dx = 0 redraw_cb() return self._shake_dx = self.SHAKE_OFFSETS_PX[idx] redraw_cb() try: self._shake_job = self.root.after( self.SHAKE_STEP_MS, lambda: _step_shake(idx + 1) ) except Exception: self._shake_job = None _step_shake(0)