the_goth_cardgame_collection/games/solitaire/base/card_animator.py

172 lines
5.1 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
# games/solitaire/base/card_animator.py
from __future__ import annotations
import time
import tkinter as tk
from typing import Callable
class CardFlightAnimator:
"""
Schneller, nicht-blockierender Canvas-Animator für gleitende Kartenbewegungen.
Nutzt Canvas-Tag-Verschiebung (canvas.move) ohne teures Neu-Rendern des Hintergrunds.
"""
FRAME_MS = 14 # ~70 FPS Zielrate auf Tkinter
def __init__(self, root: tk.Misc, canvas: tk.Canvas):
self.root = root
self.canvas = canvas
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
@property
def is_active(self) -> bool:
return self._job is not None
def cancel(self):
"""Bricht laufende Timer sofort ab (z. B. beim Schließen des Fensters)."""
if self._job is not None:
try:
self.root.after_cancel(self._job)
except Exception:
pass
self._job = None
try:
if self.canvas.winfo_exists():
self.canvas.delete("anim_flight")
except Exception:
pass
self._flights.clear()
self._on_done = None
def flush(self):
"""
Beendet eine laufende Animation sofort sauber im Zielzustand,
damit schnelle Klickfolgen des Spielers niemals ausgebremst werden.
"""
if not self.is_active:
return
cb = self._on_done
self.cancel()
if callable(cb):
cb()
def start(
self,
flights: list[dict],
draw_card_cb: Callable,
duration_ms: int = 115,
on_done: Callable[[], None] | None = None,
):
"""
flights: Liste aus Dicts:
{
"card": SolitaireCard,
"start": (x0, y0),
"end": (x1, y1),
"highlight": Optional[str],
}
"""
self.flush()
if not flights:
if callable(on_done):
on_done()
return
try:
if not self.canvas.winfo_exists():
if callable(on_done):
on_done()
return
except Exception:
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),
})
# Bei minimaler Distanz (< 4 px) direkt fertigstellen
if max_dist < 4.0:
self.canvas.delete("anim_flight")
if callable(on_done):
on_done()
return
# Kurze Wege noch knackiger, weite Wege über den ganzen Tisch minimal länger
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
try:
if not self.canvas.winfo_exists():
self._flights.clear()
self._on_done = None
return
except Exception:
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)))
# Cubic Ease-Out: spritziger Start, weiches Einrasten am Zielstapel
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