the_goth_cardgame_collection/games/solitaire/base/solitaire_canvas_input.py

374 lines
13 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
# games/solitaire/base/solitaire_canvas_input.py
from __future__ import annotations
import time
from games.solitaire.base.solitaire_core import SolitaireCard
from games.solitaire.base.solitaire_tap_prefs import (
SINGLE_TAP_MAX_HOLD_SEC,
is_single_tap_to_move_enabled,
)
from resources.code_res.game_constants import (
ACCENT_GOLD,
BORDER_COLOR,
CELL_BG,
ERROR_FG,
FONT_COLOR_TITLE_MAIN,
FONT_SIZE_BODY,
MUTED_FG,
PLAYING_CARD_SIZE,
SUBTLE_BORDER,
)
from resources.code_res.i18n import t
class SolitaireCanvasInput:
"""
Kapselt für alle Solitaire-Tische das Canvas-Frame-Rendering, Slot-/Karten-Zeichnen,
Kartenflug-Animationen sowie Maus-, Drag-&-Drop- und Tap-/Doppelklick-Steuerung.
"""
DRAG_STACK_DY_FACTOR: float = 0.195
DRAG_THRESHOLD_PX: int = 5
DOUBLE_CLICK_SEC: float = 0.30
@staticmethod
def _card_key(card: SolitaireCard) -> tuple[str, str, int]:
return (card.suit, card.rank, card.deck_id)
def _get_card_aspect(self) -> float:
if self._card_aspect is None:
sample_pil = self.ctx.assets._load_pil(
self.ctx.assets.res.get_card_back_path(self.cfg["back_color"])
)
if sample_pil and sample_pil.size[0] > 0:
self._card_aspect = sample_pil.size[1] / sample_pil.size[0]
else:
self._card_aspect = PLAYING_CARD_SIZE[1] / PLAYING_CARD_SIZE[0]
return self._card_aspect
def _on_canvas_configure(self, _event=None):
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:
try:
self.ctx.root.after_cancel(self._resize_job)
except Exception:
pass
try:
self._resize_job = self.ctx.root.after(35, self._recompute_and_draw)
except Exception:
self._resize_job = None
def _prepare_canvas_frame(
self, min_w: int = 640, min_h: int = 420
) -> tuple[int, int]:
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 keep_ids:
self.canvas.delete(item_id)
self._canvas_ui_refs.clear()
cw = max(min_w, self.canvas.winfo_width())
ch = max(min_h, self.canvas.winfo_height())
self._bg_renderer.draw_on_canvas(self.canvas, cw, ch)
return cw, ch
def _finish_canvas_frame(
self, canvas_w: int, canvas_h: int, exclude_source, hidden: set
):
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
)
bw, bh = p_ph.width() + 56, max(44, p_ph.height() + 18)
box_ph = self.ctx.assets.get_box_photo("box_purple", (bw, bh))
self._canvas_ui_refs.extend([p_ph, box_ph] if box_ph else [p_ph])
pcx, pcy = canvas_w // 2, canvas_h - bh // 2 - 18
if box_ph:
self.canvas.create_image(pcx, pcy, image=box_ph, anchor="center")
self.canvas.create_image(pcx, pcy, image=p_ph, anchor="center")
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 _draw_slot(
self,
x: int,
y: int,
symbol: str = "",
symbol_color: str = MUTED_FG,
highlight_color: str | None = None,
draw_red_cross: bool = False,
):
cw, ch = self.card_size
outline = (
ERROR_FG
if draw_red_cross
else (highlight_color if highlight_color else BORDER_COLOR)
)
width = 2 if (highlight_color or draw_red_cross) else 1
self.canvas.create_rectangle(
x, y, x + cw, y + ch, fill=CELL_BG, outline=outline, width=width
)
if draw_red_cross:
px, py = max(14, int(cw * 0.22)), max(18, int(ch * 0.22))
self.canvas.create_line(
x + px, y + py, x + cw - px, y + ch - py,
fill="#ff4455", width=4, capstyle="round",
)
self.canvas.create_line(
x + cw - px, y + py, x + px, y + ch - py,
fill="#ff4455", width=4, capstyle="round",
)
elif symbol:
self.canvas.create_text(
x + cw // 2,
y + ch // 2,
text=symbol,
font=("Georgia", max(13, cw // 4), "bold"),
fill=symbol_color,
)
def _draw_card_at(
self,
card: SolitaireCard,
x: int,
y: int,
tags: tuple[str, ...] = (),
highlight_color: str | None = None,
dim_non_movable: bool = False,
):
cw, ch = self.card_size
photo = (
self.ctx.assets.get_card_photo(card.filename, size=self.card_size)
if card.face_up
else self.ctx.assets.get_card_back_photo(
self.cfg["back_color"], size=self.card_size
)
)
if photo is not None:
self.canvas.create_image(x, y, image=photo, anchor="nw", tags=tags)
else:
fill_c = "#f5f2f8" if card.face_up else "#201a2b"
self.canvas.create_rectangle(
x, y, x + cw, y + ch, fill=fill_c, outline=BORDER_COLOR, tags=tags
)
if card.face_up:
txt_c = "#c93b4b" if card.is_red else "#16131d"
self.canvas.create_text(
x + 9, y + 11, text=card.label, anchor="nw",
font=("Georgia", 10, "bold"), fill=txt_c, tags=tags,
)
if dim_non_movable and card.face_up and not highlight_color:
self.canvas.create_rectangle(
x, y, x + cw, y + ch, outline=SUBTLE_BORDER, width=1, tags=tags
)
if highlight_color:
self.canvas.create_rectangle(
x - 2, y - 2, x + cw + 2, y + ch + 2,
outline=highlight_color, width=2, tags=tags,
)
def _run_animated_action(
self, action_fn, override_starts=None, 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()
if override_starts:
before_pos.update(override_starts)
if not action_fn():
return False
after_pos = self._snapshot_card_positions()
moved_keys = {
k
for k, end_xy in after_pos.items()
if k in before_pos
and (
abs(end_xy[0] - before_pos[k][0]) > 3
or abs(end_xy[1] - before_pos[k][1]) > 3
)
}
if not moved_keys or self.animator is None:
(after_cb if callable(after_cb) else self.redraw)()
return True
flights = [
{
"card": c,
"start": before_pos[self._card_key(c)],
"end": after_pos[self._card_key(c)],
}
for c in self._ordered_moved_cards(moved_keys)
]
self.redraw(hidden_card_keys=moved_keys)
def finish():
if self._canvas_alive():
(after_cb if callable(after_cb) else self.redraw)()
self.animator.start(
flights, self._draw_card_at, duration_ms=duration_ms, on_done=finish
)
return True
def _on_mouse_down(self, event):
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()
self._window_active = True
self._clear_hint()
hit = self._hit_test(event.x, event.y)
self._press_info = None
self._dragging = False
if not hit:
return
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 not self._press_info.get("cards")
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)
ox, oy = self._press_info["origin"]
drag_dy = max(15, int(self.card_size[1] * self.DRAG_STACK_DY_FACTOR))
for i, card in enumerate(self._press_info["cards"]):
self._draw_card_at(
card,
ox,
oy + i * drag_dy,
tags=("drag_ghost",),
highlight_color=ACCENT_GOLD if i == 0 else None,
)
dx = event.x - self._drag_last_xy[0]
dy = event.y - self._drag_last_xy[1]
self._drag_last_xy = (event.x, event.y)
self.canvas.move("drag_ghost", dx, dy)
def _on_drop_succeeded_sound(self):
self.ctx.sounds.play("click")
def _on_mouse_up(self, event):
info, was_dragging = self._press_info, self._dragging
self._press_info, self._dragging = None, False
if not info:
return
if not was_dragging:
self._handle_click(info)
return
ox, oy = info["origin"]
sx, sy = info["start_xy"]
drop_x, drop_y = ox + (event.x - sx), oy + (event.y - sy)
drag_dy = max(15, int(self.card_size[1] * self.DRAG_STACK_DY_FACTOR))
override = {
self._card_key(c): (drop_x, drop_y + i * drag_dy)
for i, c in enumerate(info["cards"])
}
if self._run_animated_action(
lambda: self._try_drop(info, drop_x, drop_y),
override_starts=override,
duration_ms=78,
after_cb=self._after_player_move,
):
self._on_drop_succeeded_sound()
else:
target_pos = self._snapshot_card_positions()
cards: list[SolitaireCard] = info["cards"]
hidden_keys = {self._card_key(c) for c in cards}
flights = [
{
"card": c,
"start": override[self._card_key(c)],
"end": target_pos.get(self._card_key(c), (ox, oy + i * drag_dy)),
}
for i, c in enumerate(cards)
]
self.redraw(hidden_card_keys=hidden_keys)
if self.animator:
self.animator.start(
flights, self._draw_card_at, duration_ms=85, on_done=self.redraw
)
else:
self.redraw()
def _dispatch_tap_or_double_click(self, info: dict):
now = time.monotonic()
if is_single_tap_to_move_enabled():
self._last_click_target = None
if (now - info.get("press_ts", now)) <= 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
self._smart_auto_move(info)
else:
self._last_click_ts = now
self._last_click_target = target_id
def _on_right_click(self, event):
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()
self._window_active = True
self._clear_hint()
hit = self._hit_test(event.x, event.y)
if hit:
self.engine.start_timer_if_needed()
self._update_hud_text()
if hit.get("zone") == "stock":
self._handle_click(hit)
else:
self._smart_auto_move(hit)