# -*- coding: utf-8 -*- # games/solitaire/base/solitaire_table_controller.py from __future__ import annotations 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_outcome_flow import SolitaireOutcomeFlow from games.solitaire.base.solitaire_session_guard import SolitaireSessionGuard from games.solitaire.base.solitaire_theme import SolitaireTableBgRenderer from resources.code_res.game_constants import ( PLAYING_CARD_SIZE, SOLITAIRE_DIFFICULTIES, TABLE_BG, ) from resources.code_res.i18n import t from view.widgets.endgame_fx_overlay import EndgameFxOverlay from view.widgets.image_button import ImageButton class SolitaireTableController(SolitaireSessionGuard): """ Gemeinsame Tisch-Basisklasse für alle Solitaire-Spiele: Baut Topbar/BottomBar/Canvas auf und steuert Undo, Hint, Auto-Complete & Neu-Geben. """ GAME_FOLDER_ID: str = "" HAS_AUTOCOMPLETE_BTN: bool = True AUTO_STEP_DELAY_MS: int = 12 AUTO_FLIGHT_MS: int = 75 SPEED_THRESHOLDS_SEC: tuple[int, int] = (180, 330) def _init_controller_state( self, context, variant_key: str, cfg: dict, difficulty: int, on_back_to_menu ): self.ctx = context self.variant_key = variant_key self.cfg = cfg self.difficulty = max(0, min(3, int(difficulty))) self.on_back_to_menu = on_back_to_menu self._alive = True self._game_concluded = False self._window_active = True self._checkpoint_ticks = 0 self._tick_job: str | None = None self._focus_job: str | None = None self._hint_job: str | None = None self._auto_job: str | None = None self._resize_job: str | None = None 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 = [] self._card_aspect: float | None = None self.card_size: tuple[int, int] = PLAYING_CARD_SIZE self._press_info: dict | None = None self._dragging: bool = False self._drag_last_xy: tuple[int, int] = (0, 0) self._last_click_ts: float = 0.0 self._last_click_target: tuple | None = None self._active_hint: dict | None = None self._modal_overlay: tk.Widget | None = None self.auto_btn: ImageButton | None = None def _finish_startup(self, is_resumed: bool): self._build_ui() if not is_resumed: self.ctx.sounds.play("deal") self._check_window_focus() self._save_progress() self._start_clock() @property def _combined_xp_mult(self) -> float: d_mult = SOLITAIRE_DIFFICULTIES.get( self.difficulty, SOLITAIRE_DIFFICULTIES[1] )["xp_mult"] return self.cfg["xp_mult"] * d_mult def _build_ui(self): self._play_table_music() self.ctx.root.clear_window(apply_global_bg=True) self.ctx.refresh_game_progress() self.topbar = self.ctx.build_game_topbar( self.ctx.root, stats_endpoint=self.GAME_FOLDER_ID, stats_enabled=True, on_lang_refresh=self._refresh_lang, on_stats_back=self._schedule_focus_check, ) self.hud_var = tk.StringVar(value="") self.status_var = tk.StringVar(value="") self.bottom_bar = SolitaireBottomBar( self.ctx.root, self.ctx, self.hud_var, self.status_var ) self.bottom_bar.pack(fill="x", side="bottom", padx=14, pady=(4, 10)) btn_norm = self.ctx.assets.raw_btn_default btn_purp = self.ctx.assets.raw_btn_purple btn_fire = self.ctx.assets.raw_btn_fire or btn_purp self.undo_btn = ImageButton( self.bottom_bar, t("sol_btn_undo"), btn_norm, btn_purp, self._on_undo, sound_mgr=self.ctx.sounds, width=136, height=32, enabled=self.engine.can_undo, style="amethyst", ) self.undo_all_btn = ImageButton( self.bottom_bar, t("sol_btn_undo_all"), btn_norm, btn_purp, self._on_undo_all, sound_mgr=self.ctx.sounds, width=92, height=32, enabled=self.engine.can_undo_all, style="amethyst", ) self.hint_btn = ImageButton( self.bottom_bar, t("sol_btn_hint"), btn_norm, btn_purp, self._on_hint, sound_mgr=self.ctx.sounds, width=92, height=32, enabled=not self.engine.won, style="amethyst", ) main_btns = [self.undo_btn, self.undo_all_btn, self.hint_btn] if self.HAS_AUTOCOMPLETE_BTN: self.auto_btn = ImageButton( self.bottom_bar, t("sol_btn_autocomplete"), btn_fire, btn_fire, self._start_auto_complete, sound_mgr=self.ctx.sounds, width=112, height=32, enabled=self.engine.can_auto_complete(), style="fire", ) main_btns.append(self.auto_btn) self.new_btn = ImageButton( self.bottom_bar, t("sol_btn_forfeit") if self.engine.moves > 0 else t("sol_btn_new_deal"), 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(main_btns, 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) self.canvas.bind("", self._on_mouse_down) self.canvas.bind("", self._on_mouse_move) self.canvas.bind("", self._on_mouse_up) self.canvas.bind("", self._on_right_click) self._bind_root("", lambda _e: self._run_undo_shortcut(False)) self._bind_root("", lambda _e: self._run_undo_shortcut(True)) self._bind_root("", lambda _e: self._run_undo_shortcut(True)) self._bind_root("", lambda _e: self._on_hint()) self._bind_root("", lambda _e: self._on_hint()) self._bind_root("", self._schedule_focus_check) self._bind_root("", self._schedule_focus_check) self._update_hud_text() def _run_undo_shortcut(self, all_moves: bool) -> str: if self._fx_overlay is not None or self._game_concluded or self._auto_running: return "break" can_act = self.engine.can_undo_all if all_moves else self.engine.can_undo if can_act: if self._modal_overlay is not None: self._close_active_modal() self.ctx.sounds.play("click") (self._on_undo_all if all_moves else self._on_undo)() return "break" def _sync_buttons(self): if not self._canvas_alive(): return 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) if self.auto_btn is not None: self.auto_btn.set_enabled((not locked) and self.engine.can_auto_complete()) 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: self.bottom_bar.relayout() self._update_hud_text() def _status_after_move(self) -> str: return "" def _after_player_move(self): self.status_var.set(self._status_after_move()) self._checkpoint_ticks = 0 self.redraw() if self.engine.won: SolitaireOutcomeFlow.handle_victory(self) return self._save_progress() self._check_deadlock_and_prompt() def _check_deadlock_and_prompt(self): if not self._is_ui_locked() and not self.engine.has_any_meaningful_move(): SolitaireOutcomeFlow.show_deadlock_modal(self) def _on_undo(self): if self._is_ui_locked(): return self._clear_hint() def _done(): self.status_var.set("") self._checkpoint_ticks = 0 self._save_progress() self.redraw() self._run_animated_action(self.engine.undo, duration_ms=105, after_cb=_done) def _on_undo_all(self): if self._is_ui_locked(): return if self.animator: self.animator.flush() self._clear_hint() if self.engine.undo_all(): self.status_var.set("") self._checkpoint_ticks = 0 self._save_progress() self.redraw() def _clear_hint(self): if self._hint_job is not None: try: self.ctx.root.after_cancel(self._hint_job) except Exception: pass self._hint_job = None self._active_hint = None def _on_hint(self): if self._is_ui_locked(): return if self.animator: self.animator.flush() self._clear_hint() self.engine.start_timer_if_needed() self._update_hud_text() hint = self.engine.get_hint() if not hint: self.status_var.set(t("sol_no_hint_msg")) self._check_deadlock_and_prompt() return self.status_var.set("") self._active_hint = hint self.redraw() self._hint_job = self.ctx.root.after(1600, self._expire_hint) def _expire_hint(self): self._hint_job = None self._active_hint = None if self._canvas_alive() and self._fx_overlay is None: self.redraw() def _start_auto_complete(self): if ( not self.HAS_AUTOCOMPLETE_BTN or not self.engine.can_auto_complete() or self._is_ui_locked() ): return if self.animator: self.animator.flush() self._clear_hint() self.engine.push_undo() self._save_progress() self._auto_running = True self._sync_buttons() self._step_auto_complete() def _step_auto_complete(self): if not self._canvas_alive(): return def after_step(): if not self._canvas_alive(): return self.redraw() if not self.engine.won: self._auto_job = self.ctx.root.after( self.AUTO_STEP_DELAY_MS, self._step_auto_complete ) else: self._auto_running, self._auto_job = False, None SolitaireOutcomeFlow.handle_victory(self) if self._run_animated_action( lambda: bool(self.engine.auto_complete_step(record_undo=False)), duration_ms=self.AUTO_FLIGHT_MS, after_cb=after_step, ): self.ctx.sounds.play("click") else: self._auto_running, self._auto_job = False, None self.redraw() if self.engine.won: SolitaireOutcomeFlow.handle_victory(self) else: self._save_progress() def _start_fresh_deal(self): self._game_concluded = False self._reset_engine_for_new_deal() self._check_window_focus() self._save_progress() self.status_var.set("") self.ctx.sounds.play("deal") self.redraw() def _on_new_or_forfeit_clicked(self): 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._game_concluded or self.engine.moves == 0: self._start_fresh_deal() return SolitaireOutcomeFlow.show_forfeit_modal(self) def _reset_engine_for_new_deal(self): raise NotImplementedError def _recompute_and_draw(self): raise NotImplementedError def redraw(self, exclude_source=None, hidden_card_keys=None): raise NotImplementedError def _snapshot_card_positions(self) -> dict: raise NotImplementedError def _ordered_moved_cards(self, moved_keys: set) -> list[SolitaireCard]: raise NotImplementedError def _hover_card_probe(self, x: int, y: int) -> dict | None: raise NotImplementedError def _hit_test(self, x: int, y: int) -> dict | None: raise NotImplementedError def _handle_click(self, info: dict): raise NotImplementedError def _smart_auto_move(self, info: dict): raise NotImplementedError def _try_drop(self, info: dict, drop_x: int, drop_y: int) -> bool: raise NotImplementedError