diff --git a/games/solitaire/base/__pycache__/solitaire_core.cpython-311.pyc b/games/solitaire/base/__pycache__/solitaire_core.cpython-311.pyc index 8421c1d..dba0076 100644 Binary files a/games/solitaire/base/__pycache__/solitaire_core.cpython-311.pyc and b/games/solitaire/base/__pycache__/solitaire_core.cpython-311.pyc differ diff --git a/games/solitaire/base/__pycache__/solitaire_stats_view.cpython-311.pyc b/games/solitaire/base/__pycache__/solitaire_stats_view.cpython-311.pyc index 2aeebd3..88b43b0 100644 Binary files a/games/solitaire/base/__pycache__/solitaire_stats_view.cpython-311.pyc and b/games/solitaire/base/__pycache__/solitaire_stats_view.cpython-311.pyc differ diff --git a/games/solitaire/base/__pycache__/solitaire_theme.cpython-311.pyc b/games/solitaire/base/__pycache__/solitaire_theme.cpython-311.pyc new file mode 100644 index 0000000..37de268 Binary files /dev/null and b/games/solitaire/base/__pycache__/solitaire_theme.cpython-311.pyc differ diff --git a/games/solitaire/base/solitaire_stats_view.py b/games/solitaire/base/solitaire_stats_view.py index 902df52..1997693 100644 --- a/games/solitaire/base/solitaire_stats_view.py +++ b/games/solitaire/base/solitaire_stats_view.py @@ -24,6 +24,9 @@ from view.widgets.image_button import ImageButton SHORT_VARIANT_TAB_KEYS: dict[str, str] = { "klondike_1": "kl_draw_toggle_1", "klondike_3": "kl_draw_toggle_3", + "spider_1suit": "sp_suit_toggle_1", + "spider_2suit": "sp_suit_toggle_2", + "spider_4suit": "sp_suit_toggle_4", } diff --git a/games/solitaire/base/solitaire_theme.py b/games/solitaire/base/solitaire_theme.py new file mode 100644 index 0000000..8d12bd1 --- /dev/null +++ b/games/solitaire/base/solitaire_theme.py @@ -0,0 +1,181 @@ +# -*- coding: utf-8 -*- +# games/solitaire/base/solitaire_theme.py +from __future__ import annotations + +import warnings +from pathlib import Path +from PIL import Image, ImageChops, ImageDraw, ImageTk + +_ICON_PIL_CACHE: dict[Path, Image.Image] = {} +_ICON_TK_CACHE: dict[tuple[Path, int], ImageTk.PhotoImage] = {} + + +def _extract_best_ico_pil(icon_path: Path) -> Image.Image | None: + try: + with warnings.catch_warnings(): + warnings.simplefilter("ignore", UserWarning) + with Image.open(icon_path) as ico: + best_img = None + best_area = -1 + ico_helper = getattr(ico, "ico", None) + if ico_helper is not None and hasattr(ico_helper, "sizes"): + for sz in ico_helper.sizes(): + try: + frame = ico_helper.getimage(sz).convert("RGBA") + area = frame.width * frame.height + if area > best_area: + best_area = area + best_img = frame + except Exception: + continue + if best_img is None: + for idx in range(getattr(ico, "n_frames", 1)): + try: + ico.seek(idx) + frame = ico.copy().convert("RGBA") + area = frame.width * frame.height + if area > best_area: + best_area = area + best_img = frame + except Exception: + continue + return best_img if best_img is not None else ico.convert("RGBA") + except Exception: + return None + + +def _auto_crop_and_round_badge(img: Image.Image) -> Image.Image: + """ + Schneidet weiße/transparente Außenränder (und eventuelle Text-Artefakte ganz oben) + ab und stanzt das quadratische App-Badge sauber mit abgerundeten Ecken aus. + """ + w, h = img.size + px = img.load() + + def is_badge_pixel(r: int, g: int, b: int, a: int) -> bool: + if a < 40: + return False + # Helle/weiße Schachbrett- oder Hintergrundpixel ignorieren + if r > 228 and g > 228 and b > 228: + return False + return True + + # Suche horizontale & vertikale Ausdehnung des eigentlichen breiten Icon-Blocks + # (Zeilen mit nur wenigen schmalen Buchstaben-Pixeln < 35% Breite werden oben übersprungen!) + min_row_span = int(w * 0.38) + valid_rows: list[int] = [] + for y in range(h): + cnt = 0 + for x in range(0, w, 2): + if is_badge_pixel(*px[x, y]): + cnt += 2 + if cnt >= min_row_span: + valid_rows.append(y) + + min_col_span = int(h * 0.38) + valid_cols: list[int] = [] + for x in range(w): + cnt = 0 + for y in range(0, h, 2): + if is_badge_pixel(*px[x, y]): + cnt += 2 + if cnt >= min_col_span: + valid_cols.append(x) + + if valid_rows and valid_cols: + top, bottom = valid_rows[0], valid_rows[-1] + 1 + left, right = valid_cols[0], valid_cols[-1] + 1 + cropped = img.crop((left, top, right, bottom)) + else: + cropped = img + + # Auf sauberes Quadrat bringen & mit 2x Supersampling rund maskieren + side = max(cropped.width, cropped.height) + square = cropped.resize((side, side), Image.Resampling.LANCZOS) + + mask_big = Image.new("L", (side * 2, side * 2), 0) + draw = ImageDraw.Draw(mask_big) + radius = int(side * 2 * 0.195) + pad = int(side * 2 * 0.008) + draw.rounded_rectangle( + (pad, pad, side * 2 - 1 - pad, side * 2 - 1 - pad), + radius=radius, + fill=255, + ) + mask = mask_big.resize((side, side), Image.Resampling.LANCZOS) + + r_ch, g_ch, b_ch, a_ch = square.split() + square.putalpha(ImageChops.multiply(a_ch, mask)) + return square + + +def get_game_icon_photo(res_mgr, game_folder: str, size_px: int = 92) -> ImageTk.PhotoImage | None: + icon_path = res_mgr.get_game_icon_path(game_folder) + if icon_path is None: + return None + + cache_key = (icon_path, size_px) + if cache_key in _ICON_TK_CACHE: + return _ICON_TK_CACHE[cache_key] + + if icon_path not in _ICON_PIL_CACHE: + raw = _extract_best_ico_pil(icon_path) + if raw is None: + return None + _ICON_PIL_CACHE[icon_path] = _auto_crop_and_round_badge(raw) + + resized = _ICON_PIL_CACHE[icon_path].resize((size_px, size_px), Image.Resampling.LANCZOS) + photo = ImageTk.PhotoImage(resized) + _ICON_TK_CACHE[cache_key] = photo + return photo + + +class SolitaireTableBgRenderer: + """ + Zeichnet und cached resources/images/general_table.jpg passgenau auf das Solitaire-Canvas + und liefert die Rahmen-Abstände, damit alle Stapel sauber innerhalb des Holzrahmens sitzen. + """ + + # Prozentuale Rahmenstärke von general_table.jpg (Steinmauer + Kerzen + Holzrahmen) + FRAME_X_RATIO = 0.075 + FRAME_TOP_RATIO = 0.095 + FRAME_BOT_RATIO = 0.090 + + def __init__(self, res_mgr): + self.res_mgr = res_mgr + self._raw_pil: Image.Image | None = None + self._loaded = False + self._cached_size: tuple[int, int] = (0, 0) + self._cached_photo: ImageTk.PhotoImage | None = None + + def _ensure_pil(self) -> Image.Image | None: + if not self._loaded: + self._loaded = True + bg_path = self.res_mgr.get_ui_image_path("general_table") + if bg_path.is_file(): + try: + with Image.open(bg_path) as im: + self._raw_pil = im.convert("RGB") + except Exception: + self._raw_pil = None + return self._raw_pil + + def get_frame_insets(self, canvas_w: int, canvas_h: int) -> tuple[int, int, int]: + """Gibt (inset_x, inset_top, inset_bottom) passend zum Zierrahmen zurück.""" + if self._ensure_pil() is None: + return max(20, int(canvas_w * 0.04)), max(14, int(canvas_h * 0.022)), 16 + ix = max(36, int(canvas_w * self.FRAME_X_RATIO)) + itop = max(28, int(canvas_h * self.FRAME_TOP_RATIO)) + ibot = max(26, int(canvas_h * self.FRAME_BOT_RATIO)) + return ix, itop, ibot + + def draw_on_canvas(self, canvas, canvas_w: int, canvas_h: int): + pil_img = self._ensure_pil() + if pil_img is None or canvas_w < 50 or canvas_h < 50: + return + target_sz = (canvas_w, canvas_h) + if self._cached_photo is None or self._cached_size != target_sz: + scaled = pil_img.resize(target_sz, Image.Resampling.BILINEAR) + self._cached_photo = ImageTk.PhotoImage(scaled) + self._cached_size = target_sz + canvas.create_image(0, 0, image=self._cached_photo, anchor="nw", tags=("table_bg",)) \ 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 d06afb4..712db68 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 8471e3e..1a0ae4f 100644 --- a/games/solitaire/freecell/views/freecell_table_view.py +++ b/games/solitaire/freecell/views/freecell_table_view.py @@ -34,6 +34,7 @@ from resources.code_res.game_constants import ( ) from resources.code_res.i18n import t from view.widgets.image_button import ImageButton +from games.solitaire.base.solitaire_theme import SolitaireTableBgRenderer GAME_FOLDER_ID = "solitaire/freecell" GAME_TITLE_KEY = "game_title_freecell" @@ -87,6 +88,8 @@ class FreeCellTableView: self._bind_ids: list[tuple[str, str]] = [] self._auto_running = False self.animator: CardFlightAnimator | None = None + self._bg_renderer = SolitaireTableBgRenderer(self.ctx.assets.res) + self._frame_bot_pad: int = 18 self._card_aspect: float | None = None self.card_size: tuple[int, int] = PLAYING_CARD_SIZE @@ -512,7 +515,7 @@ class FreeCellTableView: return [] _cw, ch = self.card_size canvas_h = max(420, self.canvas.winfo_height()) - avail_h = max(180, canvas_h - self._tableau_y - 16) + avail_h = max(180, canvas_h - self._tableau_y - self._frame_bot_pad) step_cnt = max(0, count - 1) up_dy = max(16, int(ch * 0.205)) @@ -647,25 +650,25 @@ class FreeCellTableView: ch = max(420, self.canvas.winfo_height()) aspect = self._get_card_aspect() - margin_x = max(22, int(cw * 0.04)) + margin_x, top_pad, bot_pad = self._bg_renderer.get_frame_insets(cw, ch) + self._frame_bot_pad = bot_pad usable_w = cw - 2 * margin_x gap_x = max(10, int(usable_w * 0.015)) center_extra = max(16, int(gap_x * 1.8)) card_w_by_width = int((usable_w - 6 * gap_x - center_extra) / 8) - top_pad = max(14, int(ch * 0.022)) - row_gap = max(18, int(ch * 0.032)) - avail_for_cards = max(240, ch - top_pad - row_gap - 18) - max_card_h_by_height = int(avail_for_cards / 3.05) + row_gap = max(16, int(ch * 0.030)) + avail_for_cards = max(220, ch - top_pad - row_gap - bot_pad) + max_card_h_by_height = int(avail_for_cards / 3.00) card_w_by_height = int(round(max_card_h_by_height / aspect)) - card_w = max(66, min(card_w_by_width, card_w_by_height)) + card_w = max(62, min(card_w_by_width, card_w_by_height)) card_h = int(round(card_w * aspect)) self.card_size = (card_w, card_h) top_total_w = 8 * card_w + 6 * gap_x + center_extra - top_start_x = max(10, (cw - top_total_w) // 2) + top_start_x = max(margin_x, (cw - top_total_w) // 2) self._fc_x = [top_start_x + i * (card_w + gap_x) for i in range(4)] found_start_x = self._fc_x[3] + card_w + center_extra self._found_x = [found_start_x + i * (card_w + gap_x) for i in range(4)] @@ -744,6 +747,7 @@ class FreeCellTableView: cw, ch = self.card_size canvas_w = max(680, self.canvas.winfo_width()) canvas_h = max(420, self.canvas.winfo_height()) + self._bg_renderer.draw_on_canvas(self.canvas, canvas_w, canvas_h) hidden = hidden_card_keys or set() valid_drag_fc: set[int] = set() 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 d04e9db..421cd1e 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 f119cc9..9abfce4 100644 --- a/games/solitaire/klondike/views/klondike_table_view.py +++ b/games/solitaire/klondike/views/klondike_table_view.py @@ -34,6 +34,7 @@ from resources.code_res.game_constants import ( ) from resources.code_res.i18n import t from view.widgets.image_button import ImageButton +from games.solitaire.base.solitaire_theme import SolitaireTableBgRenderer GAME_FOLDER_ID = "solitaire/klondike" GAME_TITLE_KEY = "game_title_klondike" @@ -93,6 +94,8 @@ class KlondikeTableView: self._bind_ids: list[tuple[str, str]] = [] self._auto_running = False self.animator: CardFlightAnimator | None = None + self._bg_renderer = SolitaireTableBgRenderer(self.ctx.assets.res) + self._frame_bot_pad: int = 18 self._card_aspect: float | None = None self.card_size: tuple[int, int] = PLAYING_CARD_SIZE @@ -517,7 +520,8 @@ class KlondikeTableView: return [] _cw, ch = self.card_size canvas_h = max(420, self.canvas.winfo_height()) - avail_h = max(180, canvas_h - self._tableau_y - 16) + avail_h = max(180, canvas_h - self._tableau_y - self._frame_bot_pad) + down_cnt = sum(1 for c in cards if not c.face_up) up_cnt = max(0, len(cards) - down_cnt - 1) @@ -680,24 +684,24 @@ class KlondikeTableView: ch = max(420, self.canvas.winfo_height()) aspect = self._get_card_aspect() - margin_x = max(24, int(cw * 0.045)) + margin_x, top_pad, bot_pad = self._bg_renderer.get_frame_insets(cw, ch) + self._frame_bot_pad = bot_pad usable_w = cw - 2 * margin_x gap_x = max(12, int(usable_w * 0.018)) card_w_by_width = int((usable_w - 6 * gap_x) / 7) - top_pad = max(14, int(ch * 0.022)) - row_gap = max(18, int(ch * 0.032)) - avail_for_cards = max(240, ch - top_pad - row_gap - 18) - max_card_h_by_height = int(avail_for_cards / 3.05) + row_gap = max(16, int(ch * 0.030)) + avail_for_cards = max(220, ch - top_pad - row_gap - bot_pad) + max_card_h_by_height = int(avail_for_cards / 3.00) card_w_by_height = int(round(max_card_h_by_height / aspect)) - card_w = max(72, min(card_w_by_width, card_w_by_height)) + card_w = max(68, min(card_w_by_width, card_w_by_height)) card_h = int(round(card_w * aspect)) self.card_size = (card_w, card_h) total_row_w = 7 * card_w + 6 * gap_x - start_x = max(12, (cw - total_row_w) // 2) + start_x = max(margin_x, (cw - total_row_w) // 2) self._col_x = [start_x + i * (card_w + gap_x) for i in range(7)] self._top_y = top_pad self._tableau_y = self._top_y + card_h + row_gap @@ -787,6 +791,7 @@ class KlondikeTableView: cw, ch = self.card_size canvas_w = max(640, self.canvas.winfo_width()) canvas_h = max(420, self.canvas.winfo_height()) + self._bg_renderer.draw_on_canvas(self.canvas, canvas_w, canvas_h) hidden = hidden_card_keys or set() valid_drag_foundations: set[int] = set() diff --git a/games/solitaire/spider_solitaire/__init__.py b/games/solitaire/spider_solitaire/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/games/solitaire/spider_solitaire/__pycache__/__init__.cpython-311.pyc b/games/solitaire/spider_solitaire/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..13a7fb8 Binary files /dev/null and b/games/solitaire/spider_solitaire/__pycache__/__init__.cpython-311.pyc differ diff --git a/games/solitaire/spider_solitaire/__pycache__/start.cpython-311.pyc b/games/solitaire/spider_solitaire/__pycache__/start.cpython-311.pyc new file mode 100644 index 0000000..246e372 Binary files /dev/null and b/games/solitaire/spider_solitaire/__pycache__/start.cpython-311.pyc differ diff --git a/games/solitaire/spider_solitaire/models/__init__.py b/games/solitaire/spider_solitaire/models/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/games/solitaire/spider_solitaire/models/__pycache__/__init__.cpython-311.pyc b/games/solitaire/spider_solitaire/models/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..2bfb3a7 Binary files /dev/null and b/games/solitaire/spider_solitaire/models/__pycache__/__init__.cpython-311.pyc differ diff --git a/games/solitaire/spider_solitaire/models/__pycache__/spider_engine.cpython-311.pyc b/games/solitaire/spider_solitaire/models/__pycache__/spider_engine.cpython-311.pyc new file mode 100644 index 0000000..00f0f90 Binary files /dev/null and b/games/solitaire/spider_solitaire/models/__pycache__/spider_engine.cpython-311.pyc differ diff --git a/games/solitaire/spider_solitaire/models/__pycache__/spider_solver.cpython-311.pyc b/games/solitaire/spider_solitaire/models/__pycache__/spider_solver.cpython-311.pyc new file mode 100644 index 0000000..dedf4ab Binary files /dev/null and b/games/solitaire/spider_solitaire/models/__pycache__/spider_solver.cpython-311.pyc differ diff --git a/games/solitaire/spider_solitaire/models/spider_engine.py b/games/solitaire/spider_solitaire/models/spider_engine.py new file mode 100644 index 0000000..a9135c8 --- /dev/null +++ b/games/solitaire/spider_solitaire/models/spider_engine.py @@ -0,0 +1,380 @@ +# -*- coding: utf-8 -*- +# games/solitaire/spider_solitaire/models/spider_engine.py +from __future__ import annotations + +from games.solitaire.base.solitaire_core import ( + SolitaireBaseEngine, + SolitaireCard, + is_same_suit_descending, +) +from games.solitaire.spider_solitaire.models.spider_solver import generate_spider_deal +from resources.code_res.game_constants import SPIDER_VARIANTS + + +class SpiderEngine(SolitaireBaseEngine): + """ + Spider Solitaire Engine (1, 2 und 4 Farben): + - 10 Tableau-Spalten (Start: 4x 6 Karten + 6x 5 Karten = 54 Karten, oberste je offen) + - 5 Nachzieh-Pakete à 10 Karten im Stock (= 50 Karten) + - Strenge Regel: Austeilen nur erlaubt, wenn KEINE der 10 Spalten leer ist + (Ausnahme: weniger als 10 Karten insgesamt auf dem gesamten Tableau übrig) + - 8 Ablage-Slots für vollständige gleichfarbige Sequenzen (K -> A) + - Klassische Spider-Wertung: Start bei 500 Punkten, -1 pro Zug, +100 je fertiger Sequenz + """ + + NUM_TABLEAU = 10 + TOTAL_RUNS = 8 + INITIAL_SCORE = 500 + SCORE_MOVE_COST = -1 + SCORE_COMPLETED_RUN = 100 + + def __init__( + self, + variant_key: str = "spider_1suit", + difficulty: int = 1, + seed: int | None = None, + ): + super().__init__() + self.variant_key = variant_key if variant_key in SPIDER_VARIANTS else "spider_1suit" + self.difficulty = max(0, min(3, int(difficulty))) + self.seed = seed + + self.tableau: list[list[SolitaireCard]] = [[] for _ in range(self.NUM_TABLEAU)] + self.stock_deals: list[list[SolitaireCard]] = [] # Jedes Element ist eine Liste von 10 Karten + self.completed_runs: list[list[SolitaireCard]] = [] # Bis zu 8 Listen à 13 Karten (K..A) + + self.new_game(variant_key=self.variant_key, difficulty=self.difficulty, seed=seed) + + @property + def suits(self) -> tuple[str, ...]: + return SPIDER_VARIANTS[self.variant_key]["suits"] + + def new_game( + self, + variant_key: str | None = None, + difficulty: int | None = None, + seed: int | None = None, + ): + if variant_key is not None and variant_key in SPIDER_VARIANTS: + self.variant_key = variant_key + if difficulty is not None: + self.difficulty = max(0, min(3, int(difficulty))) + self.seed = seed + + self.reset_tracking() + self.score = self.INITIAL_SCORE + self.completed_runs = [] + self.tableau, self.stock_deals = generate_spider_deal( + suits=self.suits, + difficulty=self.difficulty, + seed=seed, + ) + self.capture_initial_state() + + def undo_all(self) -> bool: + """Überschreibt Score-Reset auf die Spider-typischen 500 Startpunkte.""" + if not super().undo_all(): + return False + self.score = self.INITIAL_SCORE + return True + + def _add_score(self, delta: int): + self.score = max(0, self.score + delta) + + def _reveal_top_if_needed(self, col_idx: int): + col = self.tableau[col_idx] + if col and not col[-1].face_up: + col[-1].face_up = True + + def _check_and_collect_completed_run(self, col_idx: int) -> bool: + """ + Prüft, ob am Ende von Spalte col_idx eine komplette gleichfarbige K->A-Sequenz liegt. + Falls ja, wandert sie automatisch in completed_runs (+100 Punkte). + """ + col = self.tableau[col_idx] + if len(col) < 13: + return False + tail = col[-13:] + if tail[0].value != 13 or tail[-1].value != 1: + return False + if not is_same_suit_descending(tail): + return False + + del col[-13:] + self.completed_runs.append(tail) + self._add_score(self.SCORE_COMPLETED_RUN) + self._reveal_top_if_needed(col_idx) + + if len(self.completed_runs) >= self.TOTAL_RUNS: + self.mark_won() + return True + + # --- Regel-Prüfungen --- + @property + def deals_remaining(self) -> int: + return len(self.stock_deals) + + def has_empty_column(self) -> bool: + return any(len(col) == 0 for col in self.tableau) + + def total_tableau_cards(self) -> int: + return sum(len(col) for col in self.tableau) + + def check_can_deal_row(self) -> tuple[bool, str]: + """ + Strenge Spider-Regel: + Es darf nur gegeben werden, wenn noch Pakete da sind UND alle 10 Spalten besetzt sind + (einzige Ausnahme: es liegen insgesamt weniger als 10 Karten auf dem Tisch). + """ + if self.won: + return False, "won" + if not self.stock_deals: + return False, "empty_stock" + if self.has_empty_column() and self.total_tableau_cards() >= self.NUM_TABLEAU: + return False, "empty_column" + return True, "ok" + + def can_grab_stack(self, col_idx: int, start_idx: int) -> bool: + """In Spider dürfen nur lückenlos gleichfarbig absteigende Sequenzen gemeinsam gezogen werden.""" + if not (0 <= col_idx < self.NUM_TABLEAU): + return False + col = self.tableau[col_idx] + if not (0 <= start_idx < len(col)): + return False + return is_same_suit_descending(col[start_idx:]) + + def movable_tail_start_index(self, col_idx: int) -> int: + """Gibt den obersten Index zurück, ab dem der untere Teil von col_idx als gleichfarbiger Block greifbar ist.""" + col = self.tableau[col_idx] + if not col: + return 0 + idx = len(col) - 1 + while idx > 0: + upper, lower = col[idx - 1], col[idx] + if upper.face_up and upper.suit == lower.suit and upper.value == lower.value + 1: + idx -= 1 + else: + break + return idx + + def can_move_to_tableau(self, moving_cards: list[SolitaireCard], dst_col: int) -> bool: + """Ablegen ist auf jeder Karte mit Wert + 1 erlaubt (Farbe egal!) oder in eine leere Spalte.""" + if not moving_cards or not (0 <= dst_col < self.NUM_TABLEAU): + return False + if not is_same_suit_descending(moving_cards): + return False + dst = self.tableau[dst_col] + if not dst: + return True + top = dst[-1] + return top.face_up and top.value == moving_cards[0].value + 1 + + # --- Aktionen --- + def move_tableau_to_tableau(self, src_col: int, start_idx: int, dst_col: int) -> bool: + if self.won or src_col == dst_col: + return False + if not (0 <= src_col < self.NUM_TABLEAU and 0 <= dst_col < self.NUM_TABLEAU): + return False + col = self.tableau[src_col] + if not (0 <= start_idx < len(col)): + return False + + moving = col[start_idx:] + if not self.can_move_to_tableau(moving, dst_col): + return False + + self.push_undo() + del col[start_idx:] + self.tableau[dst_col].extend(moving) + self.moves += 1 + self._add_score(self.SCORE_MOVE_COST) + self._reveal_top_if_needed(src_col) + self._check_and_collect_completed_run(dst_col) + return True + + def deal_from_stock(self) -> bool: + ok, _reason = self.check_can_deal_row() + if not ok: + return False + + self.push_undo() + pack = self.stock_deals.pop(0) + for col_idx, card in enumerate(pack): + card.face_up = True + self.tableau[col_idx].append(card) + + self.moves += 1 + # Falls durch das Austeilen direkt ein Ass eine 12er-Kette (K..2) vollendet: + for col_idx in range(self.NUM_TABLEAU): + self._check_and_collect_completed_run(col_idx) + return True + + # --- Komfort: Hinweise & Sackgassen-Erkennung --- + def has_any_meaningful_move(self) -> bool: + if self.won: + return True + + # 1. Darf direkt eine neue Reihe gegeben werden? + can_deal, _ = self.check_can_deal_row() + if can_deal: + return True + + # 2. Wenn irgendeine Spalte leer ist und eine andere Spalte >= 2 Blöcke/Karten hat, kann rangiert werden + if self.has_empty_column(): + for col_i, col in enumerate(self.tableau): + if not col: + continue + tail_start = self.movable_tail_start_index(col_i) + # Wenn über dem bewegbaren Block noch Karten liegen, bringt das Auslagern in die leere Spalte Fortschritt + if tail_start > 0: + return True + # Auch wenn wir noch Stock-Pakete haben und nur die leeren Spalten füllen müssen: + if self.stock_deals and self.total_tableau_cards() >= self.NUM_TABLEAU: + for col_i, col in enumerate(self.tableau): + if len(col) >= 2: + return True + + # 3. Sinnvolle Züge zwischen zwei belegten Spalten prüfen + for src_col, col in enumerate(self.tableau): + if not col: + continue + tail_start = self.movable_tail_start_index(col_i := src_col) + + # Prüfe sowohl den kompletten gleichfarbigen Block als auch sinnvolle Teil-Splits + for idx in range(tail_start, len(col)): + moving = col[idx:] + head = moving[0] + + for dst_col, dst in enumerate(self.tableau): + if src_col == dst_col or not dst: + continue + dst_top = dst[-1] + if dst_top.value != head.value + 1: + continue + + # Wenn wir mitten in einem bereits gleichfarbigen Block splitten (idx > tail_start), + # ist das nur sinnvoll, wenn damit auf der Zielspalte sofort alle 13 Karten (K..A) voll werden! + if idx > tail_start: + dst_tail = self.movable_tail_start_index(dst_col) + if not (dst_top.suit == head.suit and (len(dst) - dst_tail) + len(moving) == 13 and dst[dst_tail].value == 13): + continue + return True + + # Ganzer Block ab tail_start wird bewegt: + # a) Legt verdeckte Karte frei oder leert die Spalte komplett -> immer produktiv! + if tail_start == 0 or not col[tail_start - 1].face_up: + return True + + prev_card = col[tail_start - 1] + # b) Lag der Block vorher auf einer unpassenden Karte (z.B. 5 auf Bube) -> jetzt geordnet! + if prev_card.value != head.value + 1: + return True + + # c) Lag vorher gemischtfarbig (z.B. Pik-7 auf Herz-8) und zieht jetzt auf Pik-8 -> Upgrade! + if prev_card.suit != head.suit and dst_top.suit == head.suit: + return True + + # d) Legt prev_card frei, damit prev_card selbst sofort woanders angelegt werden kann? + prev_head_idx = tail_start - 1 + while prev_head_idx > 0: + u, lo = col[prev_head_idx - 1], col[prev_head_idx] + if u.face_up and u.suit == lo.suit and u.value == lo.value + 1: + prev_head_idx -= 1 + else: + break + exposed_head = col[prev_head_idx] + for third_col, third_pile in enumerate(self.tableau): + if third_col in (src_col, dst_col) or not third_pile: + continue + if third_pile[-1].value == exposed_head.value + 1: + return True + + return False + + def get_hint(self) -> dict | None: + best_hint: dict | None = None + best_prio = -1 + + for src_col, col in enumerate(self.tableau): + if not col: + continue + tail_start = self.movable_tail_start_index(src_col) + moving = col[tail_start:] + head = moving[0] + exposes_down = tail_start > 0 and not col[tail_start - 1].face_up + empties_col = tail_start == 0 + + for dst_col, dst in enumerate(self.tableau): + if src_col == dst_col: + continue + if not dst: + if empties_col: + continue + prio = 45 if exposes_down else 20 + else: + top = dst[-1] + if top.value != head.value + 1: + continue + same_suit = top.suit == head.suit + # Sinnloses Hin-und-Her unterdrücken + if tail_start > 0 and col[tail_start - 1].face_up and col[tail_start - 1].value == head.value + 1: + if col[tail_start - 1].suit == head.suit: + continue + if not same_suit: + continue + prio = (100 if same_suit else 50) + (30 if exposes_down else 0) + (20 if empties_col else 0) + + if prio > best_prio: + best_prio = prio + best_hint = { + "type": "tab_to_tab", + "src_col": src_col, + "card_idx": tail_start, + "dst_col": dst_col, + } + + if best_hint is not None: + return best_hint + + # Falls Spalten leer sind, aber noch Nachzieh-Pakete warten -> Hinweis, eine Spalte zu füllen + if self.stock_deals and self.has_empty_column() and self.total_tableau_cards() >= self.NUM_TABLEAU: + empty_dst = next(i for i, c in enumerate(self.tableau) if not c) + donor = next((i for i, c in enumerate(self.tableau) if len(c) >= 2), None) + if donor is not None: + return { + "type": "tab_to_tab", + "src_col": donor, + "card_idx": len(self.tableau[donor]) - 1, + "dst_col": empty_dst, + } + + can_deal, _ = self.check_can_deal_row() + if can_deal: + return {"type": "deal_stock"} + + return None + + # --- Persistenz --- + def serialize_board(self) -> dict: + return { + "variant_key": self.variant_key, + "difficulty": self.difficulty, + "tableau": [[c.to_dict() for c in col] for col in self.tableau], + "stock_deals": [[c.to_dict() for c in pack] for pack in self.stock_deals], + "completed_runs": [[c.to_dict() for c in run] for run in self.completed_runs], + } + + def restore_board(self, board: dict): + vk = board.get("variant_key", self.variant_key) + if vk in SPIDER_VARIANTS: + self.variant_key = vk + self.difficulty = max(0, min(3, int(board.get("difficulty", 1)))) + self.tableau = [ + [SolitaireCard.from_dict(d) for d in col] for col in board["tableau"] + ] + self.stock_deals = [ + [SolitaireCard.from_dict(d) for d in pack] for pack in board["stock_deals"] + ] + self.completed_runs = [ + [SolitaireCard.from_dict(d) for d in run] for run in board.get("completed_runs", []) + ] \ No newline at end of file diff --git a/games/solitaire/spider_solitaire/models/spider_solver.py b/games/solitaire/spider_solitaire/models/spider_solver.py new file mode 100644 index 0000000..dca8a04 --- /dev/null +++ b/games/solitaire/spider_solitaire/models/spider_solver.py @@ -0,0 +1,340 @@ +# -*- coding: utf-8 -*- +# games/solitaire/spider_solitaire/models/spider_solver.py +from __future__ import annotations + +import random + +from games.solitaire.base.solitaire_core import SOLITAIRE_RANKS, SolitaireCard + + +def _evaluate_spider_deal_hardness( + tableau: list[list[SolitaireCard]], + deals: list[list[SolitaireCard]], + num_suits: int, +) -> float: + """ + Bewertet die strukturelle Härte eines Spider-Deals: + - Könige & Asse tief verdeckt vs. günstige Startkarten oben + - Gleichfarbige Startpaare unter den 10 offenen Startkarten + - Farbbrüche in den Nachzieh-Reihen + """ + score = 0.0 + top_cards = [col[-1] for col in tableau if col] + + # 1. Start-Anschlüsse unter den 10 offenen Karten prüfen + same_suit_links = 0 + mixed_suit_links = 0 + for i, c_a in enumerate(top_cards): + if c_a.value == 1: + score += 3.5 # Ass blockiert als Spaltenspitze zu Beginn + elif c_a.value == 13: + score -= 1.5 + for j, c_b in enumerate(top_cards): + if i != j and c_a.value + 1 == c_b.value: + if c_a.suit == c_b.suit: + same_suit_links += 1 + else: + mixed_suit_links += 1 + + score -= same_suit_links * 5.0 + score -= mixed_suit_links * 2.0 + + # 2. Verdeckte Karten in den 10 Spalten bewerten + for col in tableau: + hidden = col[:-1] + depth_total = len(hidden) + for pos, card in enumerate(hidden): + depth = depth_total - pos + # Tief vergrabene hohe Bausteine (König/Dame/Bube) erschweren den Aufbau kompletter Runs + if card.value >= 11: + score += depth * 1.35 + elif card.value == 1: + score -= depth * 0.35 + + # 3. Nachzieh-Pakete: viele Asse in frühen Deals verstopfen alle 10 Spalten auf Schlag + for d_idx, pack in enumerate(deals): + early_weight = 1.4 if d_idx < 2 else 0.9 + aces = sum(1 for c in pack if c.value == 1) + kings = sum(1 for c in pack if c.value == 13) + score += aces * 3.2 * early_weight + score += kings * 1.5 * early_weight + + if num_suits == 2: + score += 18.0 + elif num_suits == 4: + score += 42.0 + + return score + + +def _build_reverse_solvable_deal( + suits: tuple[str, ...], + difficulty: int, + rng: random.Random, +) -> tuple[list[list[SolitaireCard]], list[list[SolitaireCard]]]: + """ + Konstruiert ein garantiert lösbares Spider-Deck durch kontrollierte Rückwärts-Zerlegung + aus 8 vollständigen K->A-Farbsequenzen (104 Karten): + - Auf 'Leicht' (0) und 'Normal' (1) bleiben zusammenhängende Teil-Sequenzen häufiger in + komplementären Schichten erreichbar, sodass sich früh leere Spalten öffnen lassen. + - Auf 'Schwer' (2) und 'Gottheit' (3) werden die Sequenzen stärker verschränkt und + Schlüsselkarten tiefer in die unteren Lagen und späteren Stock-Pakete gelegt. + """ + # 8 komplette Sätze à 13 Karten (deck_id 0..7 zur eindeutigen Karten-Identität für den Animator!) + runs: list[list[SolitaireCard]] = [] + for set_idx in range(8): + suit = suits[set_idx % len(suits)] + # Innerhalb eines Runs: [K, Q, J, 10, ..., 2, A] + run_cards = [ + SolitaireCard(suit=suit, rank=rank, face_up=False, deck_id=set_idx) + for rank in reversed(SOLITAIRE_RANKS) + ] + runs.append(run_cards) + + rng.shuffle(runs) + + # Chunk-Größen je Schwierigkeit: größere zusammenhängende Blöcke = deutlich flüssiger lösbar + chunk_ranges = { + 0: (3, 5), # Leicht: viele 3er- bis 5er-Ketten nahe beieinander + 1: (2, 4), # Normal: klassischer Mix + 2: (1, 3), # Schwer: feine Zerstückelung + 3: (1, 2), # Gottheit: maximale Verzahnung einzelner Karten + } + c_min, c_max = chunk_ranges.get(difficulty, (2, 4)) + + # Zerlege die 8 Runs in geordnete Fragmente (von A-Ende bis K-Kopf) + fragments: list[list[SolitaireCard]] = [] + for run in runs: + idx = 0 + while idx < len(run): + step = rng.randint(c_min, c_max) + fragments.append(run[idx : idx + step]) + idx += step + + # Mische Fragmente kontrolliert je nach Schwierigkeit + rng.shuffle(fragments) + ordered_pool: list[SolitaireCard] = [] + for frag in fragments: + if difficulty >= 2 and len(frag) > 1 and rng.random() < (0.45 if difficulty == 2 else 0.78): + frag = list(frag) + rng.shuffle(frag) + ordered_pool.extend(frag) + + # Leichte Nachmischung mit lokalem Fenster, damit keine künstlichen Muster sichtbar sind, + # die Schicht-Erreichbarkeit (Könige/Mittelkarten nicht alle ganz unten begraben) aber erhalten bleibt + window = {0: 8, 1: 18, 2: 36, 3: 68}.get(difficulty, 18) + n = len(ordered_pool) + swaps = {0: 28, 1: 55, 2: 95, 3: 160}.get(difficulty, 55) + for _ in range(swaps): + i = rng.randrange(n) + j = min(n - 1, max(0, i + rng.randint(-window, window))) + ordered_pool[i], ordered_pool[j] = ordered_pool[j], ordered_pool[i] + + # Stelle sicher, dass unter den 10 offenen Startkarten sofort mindestens N produktive Züge liegen + # Tableau hat 54 Karten (Spalten 0..3: je 6 Karten, Spalten 4..9: je 5 Karten) -> Indizes der 10 Top-Karten: + col_lengths = [6, 6, 6, 6, 5, 5, 5, 5, 5, 5] + tableau: list[list[SolitaireCard]] = [] + cursor = 0 + for length in col_lengths: + col = ordered_pool[cursor : cursor + length] + cursor += length + for c in col: + c.face_up = False + col[-1].face_up = True + tableau.append(col) + + # Verbleibende 50 Karten -> 5 Nachzieh-Pakete à 10 Karten + deals: list[list[SolitaireCard]] = [] + for _ in range(5): + pack = ordered_pool[cursor : cursor + 10] + cursor += 10 + for c in pack: + c.face_up = False + deals.append(pack) + + return tableau, deals + + +def _count_initial_valid_moves(tableau: list[list[SolitaireCard]]) -> tuple[int, int]: + """Zählt (gleichfarbige Züge, gemischtfarbige Züge) direkt zum Spielstart.""" + same_m = 0 + any_m = 0 + tops = [col[-1] for col in tableau if col] + for i, a in enumerate(tops): + for j, b in enumerate(tops): + if i != j and a.value + 1 == b.value: + any_m += 1 + if a.suit == b.suit: + same_m += 1 + return same_m, any_m + + +def _greedy_rollout_check( + tableau: list[list[SolitaireCard]], + deals: list[list[SolitaireCard]], + num_suits: int, +) -> tuple[bool, int]: + """ + Schneller Vorwärts-Plausibilitätscheck (Rollout-Heuristik), der sicherstellt, + dass der Start nicht blockiert ist und sich Sequenzen sowie freie Spalten aufbauen lassen. + """ + sim_tab = [[SolitaireCard(c.suit, c.rank, c.face_up, c.deck_id) for c in col] for col in tableau] + sim_deals = [[SolitaireCard(c.suit, c.rank, False, c.deck_id) for c in p] for p in deals] + completed = 0 + empty_opened = False + + def strip_completed(col: list[SolitaireCard]) -> int: + if len(col) < 13: + return 0 + tail = col[-13:] + s0 = tail[0].suit + if all(c.face_up and c.suit == s0 and c.value == 13 - k for k, c in enumerate(tail)): + del col[-13:] + if col and not col[-1].face_up: + col[-1].face_up = True + return 1 + return 0 + + def movable_tail_start(col: list[SolitaireCard]) -> int: + idx = len(col) - 1 + while idx > 0: + upper, lower = col[idx - 1], col[idx] + if upper.face_up and upper.suit == lower.suit and upper.value == lower.value + 1: + idx -= 1 + else: + break + return idx + + seen_hashes: set[tuple] = set() + for _step in range(220): + state_sig = tuple(tuple((c.suit, c.value, c.face_up) for c in col) for col in sim_tab) + (len(sim_deals),) + if state_sig in seen_hashes: + pass + seen_hashes.add(state_sig) + + best_move: tuple[int, int, int, int] | None = None + for src_i, col in enumerate(sim_tab): + if not col: + empty_opened = True + continue + start_i = movable_tail_start(col) + head = col[start_i] + exposes_hidden = start_i > 0 and not col[start_i - 1].face_up + empties_col = start_i == 0 + + for dst_i, dst in enumerate(sim_tab): + if src_i == dst_i: + continue + if not dst: + if empties_col: + continue + prio = 45 if exposes_hidden else 18 + else: + top = dst[-1] + if top.value != head.value + 1: + continue + same_s = top.suit == head.suit + # Vermeide endloses Umlegen ohne Gewinn + if start_i > 0 and col[start_i - 1].face_up and col[start_i - 1].value == head.value + 1: + if col[start_i - 1].suit == head.suit and not same_s: + continue + if col[start_i - 1].suit == top.suit: + continue + prio = (90 if same_s else 35) + (30 if exposes_hidden else 0) + (25 if empties_col else 0) + + cand_State = None + if best_move is None or prio > best_move[0]: + # Prüfe kurz, ob dieser Zug eine Endlosschleife erzeugt + test_tab = [list(c) for c in sim_tab] + mv = test_tab[src_i][start_i:] + del test_tab[src_i][start_i:] + test_tab[dst_i].extend(mv) + if test_tab[src_i] and not test_tab[src_i][-1].face_up: + test_tab[src_i][-1] = SolitaireCard( + test_tab[src_i][-1].suit, test_tab[src_i][-1].rank, True, test_tab[src_i][-1].deck_id + ) + cand_sig = tuple(tuple((c.suit, c.value, c.face_up) for c in cc) for cc in test_tab) + (len(sim_deals),) + if cand_sig not in seen_hashes: + best_move = (prio, src_i, start_i, dst_i) + + if best_move is not None: + _p, s_i, st_i, d_i = best_move + moving = sim_tab[s_i][st_i:] + del sim_tab[s_i][st_i:] + sim_tab[d_i].extend(moving) + if sim_tab[s_i] and not sim_tab[s_i][-1].face_up: + sim_tab[s_i][-1].face_up = True + if not sim_tab[s_i]: + empty_opened = True + completed += strip_completed(sim_tab[d_i]) + if completed == 8: + return True, 8 + continue + + # Kein direkter Zug mehr -> falls erlaubt, nächstes 10er-Paket geben + if sim_deals: + total_cards = sum(len(c) for c in sim_tab) + if all(len(c) > 0 for c in sim_tab) or total_cards < 10: + pack = sim_deals.pop(0) + for col_i, card in enumerate(pack): + card.face_up = True + sim_tab[col_i].append(card) + completed += strip_completed(sim_tab[col_i]) + if completed == 8: + return True, 8 + continue + break + + min_req_runs = 2 if num_suits == 1 else (1 if num_suits == 2 else 0) + ok = (completed >= min_req_runs) and (empty_opened or completed >= 1 or num_suits == 4) + return ok, completed + + +def generate_spider_deal( + suits: tuple[str, ...], + difficulty: int = 1, + seed: int | None = None, +) -> tuple[list[list[SolitaireCard]], list[list[SolitaireCard]]]: + """ + Liefert (tableau[10], stock_deals[5][10]) für 1, 2 oder 4 Farben und Schwierigkeitsstufe 0..3. + """ + rng = random.Random(seed) if seed is not None else random.Random() + diff = max(0, min(3, int(difficulty))) + num_suits = len(suits) + + min_same_moves = {0: 3, 1: 2, 2: 1, 3: 0}[diff] + min_any_moves = {0: 4, 1: 3, 2: 2, 3: 1}[diff] + + candidates: list[tuple[float, list[list[SolitaireCard]], list[list[SolitaireCard]]]] = [] + + for _attempt in range(75): + tab, deals = _build_reverse_solvable_deal(suits, diff, rng) + same_m, any_m = _count_initial_valid_moves(tab) + if any_m < min_any_moves or (num_suits <= 2 and same_m < min_same_moves): + continue + + passed, sim_runs = _greedy_rollout_check(tab, deals, num_suits) + if not passed and diff <= 1: + continue + + h_score = _evaluate_spider_deal_hardness(tab, deals, num_suits) - sim_runs * 6.0 + candidates.append((h_score, tab, deals)) + if len(candidates) >= 5: + break + + if not candidates: + tab, deals = _build_reverse_solvable_deal(suits, diff, rng) + return tab, deals + + if diff == 0: + _, best_tab, best_deals = min(candidates, key=lambda x: x[0]) + elif diff == 3: + _, best_tab, best_deals = max(candidates, key=lambda x: x[0]) + elif diff == 1: + candidates.sort(key=lambda x: x[0]) + _, best_tab, best_deals = candidates[len(candidates) // 3] + else: + candidates.sort(key=lambda x: x[0]) + _, best_tab, best_deals = candidates[(2 * len(candidates)) // 3] + + return best_tab, best_deals \ No newline at end of file diff --git a/games/solitaire/spider_solitaire/start.py b/games/solitaire/spider_solitaire/start.py new file mode 100644 index 0000000..416e87b --- /dev/null +++ b/games/solitaire/spider_solitaire/start.py @@ -0,0 +1,12 @@ +# -*- coding: utf-8 -*- +# games/solitaire/spider_solitaire/start.py +from games.solitaire.spider_solitaire.views.spider_menu_view import SpiderMenuView +from resources.code_res.game_constants import CAT_SOLO + +GAME_TITLE_KEY = "game_title_spider_solitaire" +GAME_FOLDER_ID = "solitaire/spider_solitaire" +GAME_CATEGORY = CAT_SOLO + + +def start_game(context): + SpiderMenuView(context).show(ask_resume_popup=True) \ No newline at end of file diff --git a/games/solitaire/spider_solitaire/views/__init__.py b/games/solitaire/spider_solitaire/views/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/games/solitaire/spider_solitaire/views/__pycache__/__init__.cpython-311.pyc b/games/solitaire/spider_solitaire/views/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..c9bd550 Binary files /dev/null and b/games/solitaire/spider_solitaire/views/__pycache__/__init__.cpython-311.pyc differ diff --git a/games/solitaire/spider_solitaire/views/__pycache__/spider_menu_view.cpython-311.pyc b/games/solitaire/spider_solitaire/views/__pycache__/spider_menu_view.cpython-311.pyc new file mode 100644 index 0000000..4e865af Binary files /dev/null and b/games/solitaire/spider_solitaire/views/__pycache__/spider_menu_view.cpython-311.pyc differ 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 new file mode 100644 index 0000000..93a3370 Binary files /dev/null and b/games/solitaire/spider_solitaire/views/__pycache__/spider_table_view.cpython-311.pyc differ diff --git a/games/solitaire/spider_solitaire/views/spider_menu_view.py b/games/solitaire/spider_solitaire/views/spider_menu_view.py new file mode 100644 index 0000000..6189942 --- /dev/null +++ b/games/solitaire/spider_solitaire/views/spider_menu_view.py @@ -0,0 +1,553 @@ +# -*- coding: utf-8 -*- +# games/solitaire/spider_solitaire/views/spider_menu_view.py +from __future__ import annotations + +import json +import tkinter as tk +from tkinter import ttk + +from games.solitaire.base.solitaire_stats_view import SolitaireStatsView +from games.solitaire.spider_solitaire.views.spider_table_view import SpiderTableView +from models.database import Database +from models.progression import Progression +from resources.code_res.game_constants import ( + ACCENT_GOLD, + ACCENT_GOTH, + BG_COLOR, + BORDER_COLOR, + CELL_BG, + ERROR_FG, + FG_COLOR, + MODAL_BG, + MUTED_FG, + PANEL_BG, + SOLITAIRE_DIFFICULTIES, + SOLO_FORFEIT_XP_RATIO, + SPIDER_VARIANTS, + SUBTLE_BORDER, +) +from resources.code_res.i18n import t +from view.widgets.image_button import ImageButton + +GAME_FOLDER_ID = "solitaire/spider_solitaire" +GAME_TITLE_KEY = "game_title_spider_solitaire" + + +class SpiderMenuView: + def __init__(self, context): + self.ctx = context + self._modal_overlay: tk.Frame | None = None + self._return_bind_id: str | None = None + + def _clear_modal(self): + if self._return_bind_id is not None: + try: + self.ctx.root.unbind("", self._return_bind_id) + except Exception: + pass + self._return_bind_id = None + if self._modal_overlay is not None: + try: + self._modal_overlay.destroy() + except Exception: + pass + self._modal_overlay = None + + def show( + self, + status_msg: str = "", + status_is_ok: bool = False, + ask_resume_popup: bool = False, + ): + self._clear_modal() + pid = self.ctx.profile["id"] + self.ctx.sounds.play_menu_music() + self.ctx.root.clear_window(apply_global_bg=True) + prog = self.ctx.refresh_game_progress() + + diff_setting_key = f"spider_diff_{pid}" + var_setting_key = f"spider_variant_{pid}" + + saved_diff_str = Database.load_setting(diff_setting_key, "1") + selected_diff = ( + int(saved_diff_str) + if saved_diff_str.isdigit() and int(saved_diff_str) in SOLITAIRE_DIFFICULTIES + else 1 + ) + + selected_variant = Database.load_setting(var_setting_key, "spider_1suit") + if selected_variant not in SPIDER_VARIANTS: + selected_variant = "spider_1suit" + + def open_stats(): + self._clear_modal() + variants = Database.get_variants_for_filter(GAME_FOLDER_ID) + pre_id = next((v["id"] for v in variants if v["variant_key"] == selected_variant), None) + SolitaireStatsView( + self.ctx, + game_folder=GAME_FOLDER_ID, + game_title_key=GAME_TITLE_KEY, + on_back=lambda: self.show(), + ).show(preselect_variant_id=pre_id) + + rank_badge = f"{prog['title']} (Lv. {prog['level']} • {prog['current_xp']}/{prog['needed_xp']} XP)" + self.ctx.build_game_topbar( + self.ctx.root, + t("sp_menu_topbar"), + on_game_menu=None, + on_stats=open_stats, + stats_enabled=True, + extra_right_text=rank_badge, + on_lang_refresh=lambda: self.show(status_msg=status_msg, status_is_ok=status_is_ok), + ) + + container = tk.Frame(self.ctx.root, bg=BG_COLOR, padx=24, pady=14) + container.place(relx=0.5, rely=0.53, anchor="center", relwidth=0.88, relheight=0.84) + + main_card = tk.Frame( + container, + bg=PANEL_BG, + padx=26, + pady=20, + highlightthickness=1, + highlightbackground=BORDER_COLOR, + ) + main_card.pack(fill="x") + + tk.Label( + main_card, + text=t(GAME_TITLE_KEY), + font=("Georgia", 18, "bold"), + fg=ACCENT_GOLD, + bg=PANEL_BG, + ).pack(anchor="w") + + tk.Label( + main_card, + text=t("sp_menu_subtitle"), + font=("Helvetica", 10), + fg=MUTED_FG, + bg=PANEL_BG, + ).pack(anchor="w", pady=(4, 14)) + + if status_msg: + tk.Label( + main_card, + text=status_msg, + font=("Helvetica", 10, "bold"), + fg="#7be08a" if status_is_ok else ERROR_FG, + bg=PANEL_BG, + ).pack(anchor="w", pady=(0, 12)) + + saved = Database.load_game_state(pid, GAME_FOLDER_ID) + saved_meta = self._parse_saved_meta(saved) + + if saved and saved_meta is not None: + resume_box = tk.Frame( + main_card, + bg=CELL_BG, + padx=18, + pady=12, + highlightthickness=1, + highlightbackground=ACCENT_GOTH, + ) + resume_box.pack(fill="x", pady=(0, 16)) + + left_info = tk.Frame(resume_box, bg=CELL_BG) + left_info.pack(side="left", fill="x", expand=True) + + tk.Label( + left_info, + text=t("sol_resume_box_title"), + font=("Georgia", 12, "bold"), + fg=ACCENT_GOTH, + bg=CELL_BG, + ).pack(anchor="w") + + tk.Label( + left_info, + text=t( + "sol_resume_info", + t(f"variant_{saved['variant_key']}"), + t(f"sol_diff_short_{saved_meta['difficulty']}"), + saved_meta["moves"], + saved_meta["score"], + Database.format_seconds(saved_meta["elapsed_sec"]), + ), + font=("Helvetica", 10), + fg=FG_COLOR, + bg=CELL_BG, + ).pack(anchor="w", pady=(4, 0)) + + ImageButton( + resume_box, + t("sol_resume_btn"), + self.ctx.assets.raw_btn, + self.ctx.assets.raw_btn_active, + lambda: self._resume_saved(saved, saved_meta["difficulty"]), + sound_mgr=self.ctx.sounds, + width=185, + height=36, + font=("Helvetica", 10, "bold"), + ).pack(side="right", padx=(12, 0)) + + tk.Label( + main_card, + text=t("sol_setup_sec_title"), + font=("Georgia", 12, "bold"), + fg=ACCENT_GOTH, + bg=PANEL_BG, + ).pack(anchor="w", pady=(2, 8)) + + setup_box = tk.Frame( + main_card, + bg=CELL_BG, + padx=20, + pady=18, + highlightthickness=1, + highlightbackground=SUBTLE_BORDER, + ) + setup_box.pack(fill="x") + + # Zeile 1: 1 / 2 / 4 Farben Direkt-Umschalter + suit_row = tk.Frame(setup_box, bg=CELL_BG) + suit_row.pack(fill="x", pady=(0, 8)) + + tk.Label( + suit_row, + text=t("sp_suit_mode_lbl"), + width=16, + anchor="w", + font=("Helvetica", 10, "bold"), + fg=FG_COLOR, + bg=CELL_BG, + ).pack(side="left") + + def switch_suit_mode(v_key: str): + if v_key == selected_variant or self._modal_overlay is not None: + return + Database.save_setting(var_setting_key, v_key) + self.show(status_msg=status_msg, status_is_ok=status_is_ok) + + suit_toggles = ( + ("spider_1suit", "sp_suit_toggle_1"), + ("spider_2suit", "sp_suit_toggle_2"), + ("spider_4suit", "sp_suit_toggle_4"), + ) + for v_key, lbl_key in suit_toggles: + is_sel = selected_variant == v_key + raw_norm = self.ctx.assets.raw_btn_active if is_sel else self.ctx.assets.raw_sel + raw_act = self.ctx.assets.raw_btn_active if is_sel else self.ctx.assets.raw_sel_active + ImageButton( + suit_row, + t(lbl_key), + raw_norm, + raw_act, + lambda k=v_key: switch_suit_mode(k), + sound_mgr=self.ctx.sounds, + width=165, + height=34, + font=("Helvetica", 10, "bold"), + ).pack(side="left", padx=(0, 10)) + + # Kurze Infozeile zur gewählten Farb-Variante + desc_row = tk.Frame(setup_box, bg=CELL_BG) + desc_row.pack(fill="x", pady=(0, 12)) + tk.Label(desc_row, text="", width=16, bg=CELL_BG).pack(side="left") + tk.Label( + desc_row, + text=t(f"sp_desc_{selected_variant}"), + font=("Helvetica", 9), + fg=MUTED_FG, + bg=CELL_BG, + ).pack(side="left") + + # Zeile 2: Schwierigkeitsgrad + diff_row = tk.Frame(setup_box, bg=CELL_BG) + diff_row.pack(fill="x", pady=(0, 16)) + + tk.Label( + diff_row, + text=t("sol_diff_lbl"), + width=16, + anchor="w", + font=("Helvetica", 10, "bold"), + fg=FG_COLOR, + bg=CELL_BG, + ).pack(side="left") + + diff_labels = [t(f"sol_diff_{lvl}") for lvl in sorted(SOLITAIRE_DIFFICULTIES.keys())] + diff_map = {t(f"sol_diff_{lvl}"): lvl for lvl in sorted(SOLITAIRE_DIFFICULTIES.keys())} + diff_var = tk.StringVar(value=t(f"sol_diff_{selected_diff}")) + + diff_cb = ttk.Combobox( + diff_row, + textvariable=diff_var, + values=diff_labels, + state="readonly", + font=("Helvetica", 10), + style="Goth.TCombobox", + ) + diff_cb.pack(side="left", fill="x", expand=True, ipady=3) + + def on_diff_changed(*_): + chosen = diff_map.get(diff_var.get(), 1) + Database.save_setting(diff_setting_key, str(chosen)) + + diff_cb.bind("<>", on_diff_changed) + + # Zeile 3: Start + action_row = tk.Frame(setup_box, bg=CELL_BG) + action_row.pack(fill="x") + + ImageButton( + action_row, + t("sol_start_btn"), + self.ctx.assets.raw_btn, + self.ctx.assets.raw_btn_active, + lambda: self._on_start_clicked( + selected_variant, diff_map.get(diff_var.get(), 1), saved, saved_meta + ), + sound_mgr=self.ctx.sounds, + width=210, + height=38, + font=("Helvetica", 10, "bold"), + ).pack(side="right") + + tk.Label( + main_card, + text=t("sp_controls_hint"), + font=("Helvetica", 9), + fg=MUTED_FG, + bg=PANEL_BG, + ).pack(anchor="w", pady=(14, 0)) + + if ask_resume_popup and saved and saved_meta is not None: + self._show_resume_prompt_modal(saved, saved_meta) + + @staticmethod + def _parse_saved_meta(saved: dict | None) -> dict | None: + if not saved: + return None + try: + data = json.loads(saved["state_json"]) + if data.get("won"): + return None + board = data.get("board", {}) + if not board or "tableau" not in board or "stock_deals" not in board: + return None + return { + "moves": max(0, int(data.get("moves", 0))), + "score": int(data.get("score", 500)), + "elapsed_sec": float(data.get("elapsed_sec", 0.0)), + "difficulty": max(0, min(3, int(board.get("difficulty", 1)))), + } + except Exception: + return None + + def _show_resume_prompt_modal(self, saved: dict, saved_meta: dict): + self._clear_modal() + overlay = tk.Frame( + self.ctx.root, + bg=MODAL_BG, + padx=30, + pady=24, + highlightthickness=2, + highlightbackground=ACCENT_GOTH, + ) + overlay.place(relx=0.5, rely=0.52, anchor="center") + self._modal_overlay = overlay + + tk.Label( + overlay, + text=t("sol_resume_box_title"), + font=("Georgia", 16, "bold"), + fg=ACCENT_GOLD, + bg=MODAL_BG, + ).pack(pady=(0, 10)) + + tk.Label( + overlay, + text=t( + "sol_resume_info", + t(f"variant_{saved['variant_key']}"), + t(f"sol_diff_short_{saved_meta['difficulty']}"), + saved_meta["moves"], + saved_meta["score"], + Database.format_seconds(saved_meta["elapsed_sec"]), + ), + font=("Helvetica", 11), + fg=FG_COLOR, + bg=MODAL_BG, + justify="center", + ).pack(pady=(0, 20)) + + btn_row = tk.Frame(overlay, bg=MODAL_BG) + btn_row.pack() + + def resume_now(_event=None): + self._clear_modal() + self._resume_saved(saved, saved_meta["difficulty"]) + + try: + self._return_bind_id = self.ctx.root.bind("", resume_now, add="+") + except tk.TclError: + self._return_bind_id = None + + ImageButton( + btn_row, + t("sol_resume_btn"), + self.ctx.assets.raw_btn, + self.ctx.assets.raw_btn_active, + resume_now, + sound_mgr=self.ctx.sounds, + width=190, + height=38, + font=("Helvetica", 10, "bold"), + ).pack(side="left", padx=6) + + ImageButton( + btn_row, + t("bj_popup_to_menu_btn"), + self.ctx.assets.raw_sel, + self.ctx.assets.raw_sel_active, + self._clear_modal, + sound_mgr=self.ctx.sounds, + width=175, + height=38, + font=("Helvetica", 10, "bold"), + ).pack(side="left", padx=6) + + def _resume_saved(self, saved: dict, difficulty: int): + self._clear_modal() + SpiderTableView( + self.ctx, + variant_key=saved["variant_key"], + difficulty=difficulty, + on_back_to_menu=lambda msg="", ok=False: self.show(status_msg=msg, status_is_ok=ok), + resume_state_json=saved["state_json"], + ) + + def _on_start_clicked( + self, + variant_key: str, + difficulty: int, + saved: dict | None, + saved_meta: dict | None, + ): + if self._modal_overlay is not None: + return + if saved and saved_meta and saved_meta["moves"] > 0: + self._show_overwrite_confirm_modal(variant_key, difficulty, saved, saved_meta) + return + self._launch_fresh_game(variant_key, difficulty) + + def _show_overwrite_confirm_modal( + self, + new_variant_key: str, + new_difficulty: int, + saved: dict, + saved_meta: dict, + ): + pid = self.ctx.profile["id"] + old_v = saved["variant_key"] + old_diff = saved_meta["difficulty"] + prog = Database.get_game_progress(pid, GAME_FOLDER_ID) + v_mult = SPIDER_VARIANTS.get(old_v, {"xp_mult": 1.10})["xp_mult"] + d_mult = SOLITAIRE_DIFFICULTIES.get(old_diff, SOLITAIRE_DIFFICULTIES[1])["xp_mult"] + win_xp = Progression.calculate_match_xp(prog["level"], [], "WIN", variant_mult=v_mult * d_mult) + penalty = max(2, int(round(win_xp * SOLO_FORFEIT_XP_RATIO))) + + overlay = tk.Frame( + self.ctx.root, + bg=MODAL_BG, + padx=28, + pady=22, + highlightthickness=2, + highlightbackground=ERROR_FG, + ) + overlay.place(relx=0.5, rely=0.52, anchor="center") + self._modal_overlay = overlay + + tk.Label( + overlay, + text=t("sol_forfeit_title"), + font=("Georgia", 15, "bold"), + fg=ERROR_FG, + bg=MODAL_BG, + ).pack(pady=(0, 8)) + + tk.Label( + overlay, + text=t("sol_forfeit_desc", penalty), + font=("Helvetica", 10), + fg=FG_COLOR, + bg=MODAL_BG, + wraplength=430, + justify="center", + ).pack(pady=(0, 18)) + + row = tk.Frame(overlay, bg=MODAL_BG) + row.pack() + + def forfeit_and_start(): + floor_xp = Progression.get_creator_spirit_v_floor_xp() if prog["ever_reached_deity"] else 0 + Database.record_game_result( + pid, + variant_key=old_v, + won=False, + duration_sec=saved_meta["elapsed_sec"], + points_gained=0, + ) + Database.adjust_game_points(pid, GAME_FOLDER_ID, -penalty, min_floor_xp=floor_xp) + self.ctx.refresh_game_progress() + self._clear_modal() + self._launch_fresh_game(new_variant_key, new_difficulty) + + ImageButton( + row, + t("sol_resume_btn"), + self.ctx.assets.raw_btn, + self.ctx.assets.raw_btn_active, + lambda: self._resume_saved(saved, old_diff), + sound_mgr=self.ctx.sounds, + width=165, + height=34, + font=("Helvetica", 9, "bold"), + ).pack(side="left", padx=5) + + ImageButton( + row, + t("sol_forfeit_confirm_new"), + self.ctx.assets.raw_sel, + self.ctx.assets.raw_sel_active, + forfeit_and_start, + sound_mgr=self.ctx.sounds, + width=175, + height=34, + font=("Helvetica", 9, "bold"), + ).pack(side="left", padx=5) + + ImageButton( + row, + t("bj_popup_to_menu_btn"), + self.ctx.assets.raw_sel, + self.ctx.assets.raw_sel_active, + self._clear_modal, + sound_mgr=self.ctx.sounds, + width=155, + height=34, + font=("Helvetica", 9, "bold"), + ).pack(side="left", padx=5) + + def _launch_fresh_game(self, variant_key: str, difficulty: int): + pid = self.ctx.profile["id"] + Database.save_setting(f"spider_diff_{pid}", str(difficulty)) + Database.save_setting(f"spider_variant_{pid}", variant_key) + Database.delete_game_state(pid, GAME_FOLDER_ID) + SpiderTableView( + self.ctx, + variant_key=variant_key, + difficulty=difficulty, + on_back_to_menu=lambda msg="", ok=False: self.show(status_msg=msg, status_is_ok=ok), + ) \ No newline at end of file diff --git a/games/solitaire/spider_solitaire/views/spider_table_view.py b/games/solitaire/spider_solitaire/views/spider_table_view.py new file mode 100644 index 0000000..ea2aad7 --- /dev/null +++ b/games/solitaire/spider_solitaire/views/spider_table_view.py @@ -0,0 +1,1572 @@ +# -*- coding: utf-8 -*- +# games/solitaire/spider_solitaire/views/spider_table_view.py +from __future__ import annotations + +import time +import tkinter as tk + +from games.solitaire.base.card_animator import CardFlightAnimator +from games.solitaire.base.solitaire_core import SolitaireCard +from games.solitaire.base.solitaire_stats_view import SolitaireStatsView +from games.solitaire.spider_solitaire.models.spider_engine import SpiderEngine +from models.database import Database +from models.progression import Progression +from resources.code_res.game_constants import ( + ACCENT_GOLD, + ACCENT_GOTH, + BG_COLOR, + BORDER_COLOR, + CELL_BG, + ERROR_FG, + FG_COLOR, + MODAL_BG, + MUTED_FG, + PANEL_BG, + PLAYING_CARD_SIZE, + SOLITAIRE_DIFFICULTIES, + SOLO_FORFEIT_XP_RATIO, + SPIDER_VARIANTS, + SUBTLE_BORDER, + TABLE_BG, +) +from resources.code_res.i18n import t +from view.widgets.image_button import ImageButton +from games.solitaire.base.solitaire_theme import SolitaireTableBgRenderer + +GAME_FOLDER_ID = "solitaire/spider_solitaire" +GAME_TITLE_KEY = "game_title_spider_solitaire" + + +class SpiderTableView: + DRAG_THRESHOLD_PX = 5 + DOUBLE_CLICK_SEC = 0.30 + CHECKPOINT_TICKS = 30 + + def __init__( + self, + context, + variant_key: str = "spider_1suit", + difficulty: int = 1, + on_back_to_menu=None, + resume_state_json: str | None = None, + ): + self.ctx = context + self.variant_key = variant_key if variant_key in SPIDER_VARIANTS else "spider_1suit" + self.cfg = SPIDER_VARIANTS[self.variant_key] + self.difficulty = max(0, min(3, int(difficulty))) + self.on_back_to_menu = on_back_to_menu + + if resume_state_json: + self.engine = SpiderEngine.__new__(SpiderEngine) + super(SpiderEngine, self.engine).__init__() + self.engine.variant_key = self.variant_key + self.engine.difficulty = self.difficulty + self.engine.seed = None + self.engine.tableau = [[] for _ in range(10)] + self.engine.stock_deals = [] + self.engine.completed_runs = [] + try: + self.engine.load_json(resume_state_json) + self.variant_key = self.engine.variant_key + self.cfg = SPIDER_VARIANTS[self.variant_key] + self.difficulty = self.engine.difficulty + except Exception: + self.engine.new_game(variant_key=self.variant_key, difficulty=self.difficulty) + else: + self.engine = SpiderEngine(variant_key=self.variant_key, difficulty=self.difficulty) + + 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._resize_job: str | None = None + self._gif_job: str | None = None + self._bind_ids: list[tuple[str, str]] = [] + self.animator: CardFlightAnimator | None = None + self._bg_renderer = SolitaireTableBgRenderer(self.ctx.assets.res) + self._frame_bot_pad: int = 18 + + self._card_aspect: float | None = None + self.card_size: tuple[int, int] = PLAYING_CARD_SIZE + self._col_x: list[int] = [0] * 10 + self._top_y: int = 14 + self._tableau_y: int = 178 + self._stock_bbox: tuple[int, int, int, int] = (0, 0, 0, 0) + self._tableau_card_rects: list[list[tuple[int, int, int, int]]] = [[] for _ in range(10)] + + 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.Frame | None = None + + self._build_ui() + if not resume_state_json: + 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 + + # ========================================================================= + # UI-Aufbau, Fokus-Überwachung, Exit-Save & Lifecycle + # ========================================================================= + def _canvas_alive(self) -> bool: + if not self._alive: + return False + try: + return bool(self.canvas.winfo_exists()) + except Exception: + return False + + def _play_table_music(self): + for method_name in ("play_ingame_music", "play_table_music"): + fn = getattr(self.ctx.sounds, method_name, None) + if callable(fn): + fn() + return + + def _bind_root(self, seq: str, callback): + if not seq or not seq.startswith("<") or not seq.endswith(">"): + return + try: + func_id = self.ctx.root.bind(seq, callback, add="+") + if func_id: + self._bind_ids.append((seq, func_id)) + except tk.TclError: + pass + + def _on_canvas_destroy(self, event=None): + if event is not None and event.widget is not self.canvas: + return + if not self._alive: + return + try: + self.engine.pause_timer() + if not self._game_concluded: + self._save_progress() + except Exception: + pass + self._cleanup_timers() + + def _cleanup_timers(self): + self._alive = False + self.engine.pause_timer() + if self.animator is not None: + self.animator.cancel() + for job in ( + self._tick_job, + self._focus_job, + self._hint_job, + self._resize_job, + self._gif_job, + ): + if job is not None: + try: + self.ctx.root.after_cancel(job) + except Exception: + pass + self._tick_job = self._focus_job = self._hint_job = self._resize_job = self._gif_job = None + + for seq, func_id in self._bind_ids: + try: + self.ctx.root.unbind(seq, func_id) + except Exception: + pass + self._bind_ids.clear() + + def _schedule_focus_check(self, _event=None): + if not self._canvas_alive(): + return + if self._focus_job is not None: + try: + self.ctx.root.after_cancel(self._focus_job) + except Exception: + pass + try: + self._focus_job = self.ctx.root.after(60, self._check_window_focus) + except Exception: + self._focus_job = None + + def _check_window_focus(self): + self._focus_job = None + if not self._canvas_alive(): + return + try: + is_iconic = self.ctx.root.state() == "iconic" + has_focus = (self.ctx.root.focus_displayof() is not None) and (not is_iconic) + except Exception: + return + + should_run = has_focus and (self._modal_overlay is None) and (not self.engine.won) + prev_paused = self.engine.is_timer_paused + self._window_active = has_focus + + if should_run: + self.engine.resume_timer() + else: + if not prev_paused: + self.engine.pause_timer() + self._save_progress() + + if prev_paused != self.engine.is_timer_paused: + self._update_hud_text() + if self.animator is None or not self.animator.is_active: + self.redraw() + + def _build_ui(self): + self._play_table_music() + self.ctx.root.clear_window(apply_global_bg=False) + self.ctx.root.configure(bg=BG_COLOR) + self.ctx.refresh_game_progress() + + self.topbar = self.ctx.build_game_topbar( + self.ctx.root, + f"{t(f'variant_{self.variant_key}')} • {t(f'sol_diff_short_{self.difficulty}')}", + on_game_menu=self._back_to_game_menu, + on_stats=self._open_stats, + stats_enabled=True, + extra_right_text="", + on_lang_refresh=self._refresh_lang, + ) + + ctrl_bar = tk.Frame( + self.ctx.root, + bg=PANEL_BG, + padx=14, + pady=8, + highlightthickness=1, + highlightbackground=BORDER_COLOR, + ) + ctrl_bar.pack(fill="x", padx=14, pady=(6, 4)) + + self.hud_var = tk.StringVar(value="") + tk.Label( + ctrl_bar, + textvariable=self.hud_var, + font=("Georgia", 11, "bold"), + fg=ACCENT_GOLD, + bg=PANEL_BG, + ).pack(side="left") + + self.status_var = tk.StringVar(value="") + tk.Label( + ctrl_bar, + textvariable=self.status_var, + font=("Helvetica", 9, "bold"), + fg=ACCENT_GOTH, + bg=PANEL_BG, + ).pack(side="left", padx=(14, 0)) + + btn_box = tk.Frame(ctrl_bar, bg=PANEL_BG) + btn_box.pack(side="right") + + self.undo_btn = ImageButton( + btn_box, + t("sol_btn_undo"), + self.ctx.assets.raw_sel, + self.ctx.assets.raw_sel_active, + self._on_undo, + sound_mgr=self.ctx.sounds, + width=155, + height=32, + font=("Helvetica", 9, "bold"), + enabled=self.engine.can_undo, + ) + self.undo_btn.pack(side="left", padx=3) + + self.undo_all_btn = ImageButton( + btn_box, + t("sol_btn_undo_all"), + self.ctx.assets.raw_sel, + self.ctx.assets.raw_sel_active, + self._on_undo_all, + sound_mgr=self.ctx.sounds, + width=108, + height=32, + font=("Helvetica", 9, "bold"), + enabled=self.engine.can_undo_all, + ) + self.undo_all_btn.pack(side="left", padx=3) + + self.hint_btn = ImageButton( + btn_box, + t("sol_btn_hint"), + self.ctx.assets.raw_sel, + self.ctx.assets.raw_sel_active, + self._on_hint, + sound_mgr=self.ctx.sounds, + width=105, + height=32, + font=("Helvetica", 9, "bold"), + enabled=not self.engine.won, + ) + self.hint_btn.pack(side="left", padx=3) + + self.new_btn = ImageButton( + btn_box, + t("sol_btn_forfeit") if self.engine.moves > 0 else t("sol_btn_new_deal"), + self.ctx.assets.raw_sel, + self.ctx.assets.raw_sel_active, + self._on_new_or_forfeit_clicked, + sound_mgr=self.ctx.sounds, + width=115, + height=32, + font=("Helvetica", 9, "bold"), + ) + self.new_btn.pack(side="left", padx=(3, 0)) + + self.canvas = tk.Canvas( + self.ctx.root, + bg=TABLE_BG, + highlightthickness=1, + highlightbackground=SUBTLE_BORDER, + ) + self.canvas.pack(fill="both", expand=True, padx=14, pady=(2, 12)) + self.animator = CardFlightAnimator(self.ctx.root, self.canvas) + + 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("", self._on_undo_shortcut) + self._bind_root("", self._on_undo_all_shortcut) + self._bind_root("", self._on_undo_all_shortcut) + 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 _on_undo_shortcut(self, _event=None): + if self.engine.can_undo: + if self._modal_overlay is not None: + self._close_active_modal() + self.ctx.sounds.play("click") + self._on_undo() + return "break" + + def _on_undo_all_shortcut(self, _event=None): + if self.engine.can_undo_all: + if self._modal_overlay is not None: + self._close_active_modal() + self.ctx.sounds.play("click") + self._on_undo_all() + return "break" + + def _close_active_modal(self): + if self._modal_overlay is not None: + try: + self._modal_overlay.destroy() + except Exception: + pass + self._modal_overlay = None + self._check_window_focus() + self._sync_buttons() + + def _refresh_lang(self): + if self.animator: + self.animator.flush() + self.engine.pause_timer() + self._save_progress() + state_json = self.engine.to_json() + self._cleanup_timers() + 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, + ) + + 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.animator: + self.animator.flush() + self.engine.pause_timer() + self._save_progress() + self._cleanup_timers() + if callable(self.on_back_to_menu): + self.on_back_to_menu() + + def _save_progress(self): + if self._game_concluded: + return + pid = self.ctx.profile["id"] + if self.engine.won: + Database.delete_game_state(pid, GAME_FOLDER_ID) + return + Database.save_game_state(pid, GAME_FOLDER_ID, self.variant_key, self.engine.to_json()) + + # ========================================================================= + # Uhr, stiller Zeit-Checkpoint & HUD + # ========================================================================= + def _start_clock(self): + if not self._canvas_alive(): + return + 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: + self._checkpoint_ticks += 1 + if self._checkpoint_ticks >= self.CHECKPOINT_TICKS: + self._checkpoint_ticks = 0 + self._save_progress() + + try: + self._tick_job = self.ctx.root.after(500, self._start_clock) + except Exception: + self._tick_job = None + + def _update_hud_text(self): + if not self._alive: + 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 "" + diff_label = t(f"sol_diff_short_{self.difficulty}") + base_txt = t("sol_hud_stats", self.engine.score, self.engine.moves, elapsed_str, paused_tag, diff_label) + extra_txt = t("sp_hud_extra", len(self.engine.completed_runs), self.engine.deals_remaining) + self.hud_var.set(base_txt + extra_txt) + except Exception: + pass + + def _sync_buttons(self): + if not self._canvas_alive(): + return + locked = self.engine.won or (self._modal_overlay is not None) + 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") + if hasattr(self.new_btn, "set_text"): + self.new_btn.set_text(new_lbl) + elif hasattr(self.new_btn, "configure"): + try: + self.new_btn.configure(text=new_lbl) + except Exception: + pass + self._update_hud_text() + + # ========================================================================= + # Kartenpositions-Berechnung & Animations-Helfer (104 eindeutige Karten) + # ========================================================================= + @staticmethod + def _card_key(card: SolitaireCard) -> tuple[str, str, int]: + return (card.suit, card.rank, card.deck_id) + + def _compute_tableau_ys(self, cards: list[SolitaireCard]) -> list[int]: + if not cards: + return [] + _cw, ch = self.card_size + canvas_h = max(440, self.canvas.winfo_height()) + avail_h = max(180, canvas_h - self._tableau_y - self._frame_bot_pad) + + + down_cnt = sum(1 for c in cards if not c.face_up) + up_cnt = max(0, len(cards) - down_cnt - 1) + down_dy = max(6, int(ch * 0.088)) + up_dy = max(15, int(ch * 0.195)) + + needed_span = down_cnt * down_dy + up_cnt * up_dy + ch + if needed_span > avail_h and (down_cnt + up_cnt) > 0: + scale = max(0.30, (avail_h - ch) / max(1, down_cnt * down_dy + up_cnt * up_dy)) + down_dy = max(5, int(down_dy * scale)) + up_dy = max(11, int(up_dy * scale)) + + ys: list[int] = [] + cur_y = self._tableau_y + for card in cards: + ys.append(cur_y) + cur_y += down_dy if not card.face_up else up_dy + return ys + + def _stock_pack_x(self, pack_idx: int) -> int: + cw, _ch = self.card_size + fan_dx = max(10, cw // 7) + return self._col_x[0] + pack_idx * fan_dx + + def _snapshot_card_positions(self) -> dict[tuple[str, str, int], tuple[int, int]]: + pos: dict[tuple[str, str, int], tuple[int, int]] = {} + + # 1. Nachzieh-Pakete oben links (Spalte 0..1 gefächert) + num_packs = len(self.engine.stock_deals) + for p_idx, pack in enumerate(self.engine.stock_deals): + # Das nächste zu ziehende Paket (Index 0) liegt optisch ganz rechts oben auf dem Stapel + visual_slot = (num_packs - 1) - p_idx + px = self._stock_pack_x(visual_slot) + for c in pack: + pos[self._card_key(c)] = (px, self._top_y) + + # 2. Abgeschlossene Sequenzen oben rechts (Spalten 2..9) + for r_idx, run in enumerate(self.engine.completed_runs): + rx = self._col_x[2 + min(7, r_idx)] + for c in run: + pos[self._card_key(c)] = (rx, self._top_y) + + # 3. 10 Tableau-Spalten + for col_idx in range(10): + tx = self._col_x[col_idx] + col = self.engine.tableau[col_idx] + ys = self._compute_tableau_ys(col) + for c, cy in zip(col, ys): + pos[self._card_key(c)] = (tx, cy) + + return pos + + def _ordered_moved_cards(self, moved_keys: set[tuple[str, str, int]]) -> list[SolitaireCard]: + ordered: list[SolitaireCard] = [] + for pack in reversed(self.engine.stock_deals): + for c in pack: + if self._card_key(c) in moved_keys: + ordered.append(c) + for col in self.engine.tableau: + for c in col: + if self._card_key(c) in moved_keys: + ordered.append(c) + for run in self.engine.completed_runs: + # König obenauf zeichnen, wenn eine fertige 13er-Sequenz nach oben fliegt + for c in reversed(run): + if self._card_key(c) in moved_keys: + ordered.append(c) + return ordered + + def _run_animated_action( + self, + action_fn, + override_starts: dict[tuple[str, str, int], tuple[int, int]] | None = None, + duration_ms: int = 120, + after_cb=None, + ) -> bool: + if self.animator: + self.animator.flush() + before_pos = self._snapshot_card_positions() + if override_starts: + before_pos.update(override_starts) + + ok = action_fn() + if not ok: + return False + + after_pos = self._snapshot_card_positions() + moved_keys: set[tuple[str, str, int]] = set() + for k, end_xy in after_pos.items(): + start_xy = before_pos.get(k) + if start_xy and (abs(end_xy[0] - start_xy[0]) > 3 or abs(end_xy[1] - start_xy[1]) > 3): + moved_keys.add(k) + + if not moved_keys or self.animator is None: + if callable(after_cb): + after_cb() + else: + self.redraw() + return True + + ordered_cards = self._ordered_moved_cards(moved_keys) + flights = [ + { + "card": c, + "start": before_pos[self._card_key(c)], + "end": after_pos[self._card_key(c)], + } + for c in ordered_cards + ] + + self.redraw(hidden_card_keys=moved_keys) + + def finish(): + if not self._canvas_alive(): + return + if callable(after_cb): + after_cb() + else: + self.redraw() + + self.animator.start(flights, self._draw_card_at, duration_ms=duration_ms, on_done=finish) + return True + + # ========================================================================= + # Ausgewogenes 10-Spalten-Layout & Rendering + # ========================================================================= + def _on_canvas_configure(self, _event=None): + if not self._canvas_alive(): + return + 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 _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 _recompute_and_draw(self): + self._resize_job = None + if not self._canvas_alive(): + return + cw = max(720, self.canvas.winfo_width()) + ch = max(440, self.canvas.winfo_height()) + aspect = self._get_card_aspect() + + margin_x, top_pad, bot_pad = self._bg_renderer.get_frame_insets(cw, ch) + self._frame_bot_pad = bot_pad + usable_w = cw - 2 * margin_x + gap_x = max(7, int(usable_w * 0.011)) + + card_w_by_width = int((usable_w - 9 * gap_x) / 10) + + row_gap = max(14, int(ch * 0.026)) + avail_for_cards = max(220, ch - top_pad - row_gap - bot_pad) + max_card_h_by_height = int(avail_for_cards / 3.08) + card_w_by_height = int(round(max_card_h_by_height / aspect)) + + card_w = max(54, min(card_w_by_width, card_w_by_height)) + card_h = int(round(card_w * aspect)) + self.card_size = (card_w, card_h) + + total_row_w = 10 * card_w + 9 * gap_x + start_x = max(margin_x, (cw - total_row_w) // 2) + self._col_x = [start_x + i * (card_w + gap_x) for i in range(10)] + self._top_y = top_pad + self._tableau_y = self._top_y + card_h + row_gap + + self.redraw() + + def _draw_slot( + self, + x: int, + y: int, + symbol: str = "", + symbol_color: str = MUTED_FG, + highlight_color: str | None = None, + ): + cw, ch = self.card_size + outline = highlight_color if highlight_color else BORDER_COLOR + width = 2 if highlight_color else 1 + self.canvas.create_rectangle( + x, y, x + cw, y + ch, + fill=CELL_BG, + outline=outline, + width=width, + ) + if 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 + if card.face_up: + photo = self.ctx.assets.get_card_photo(card.filename, size=self.card_size) + else: + photo = 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 + 8, y + 10, text=card.label, anchor="nw", + font=("Georgia", 10, "bold"), fill=txt_c, tags=tags, + ) + + # Dezente Rahmenmarkierung für offene Karten, die wegen Farb-Bruch aktuell eingesperrt sind + 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 redraw( + self, + exclude_source: dict | None = None, + hidden_card_keys: set[tuple[str, str, int]] | None = None, + ): + if not self._canvas_alive(): + return + self.canvas.delete("all") + cw, ch = self.card_size + canvas_w = max(720, self.canvas.winfo_width()) + canvas_h = max(440, self.canvas.winfo_height()) + self._bg_renderer.draw_on_canvas(self.canvas, canvas_w, canvas_h) + hidden = hidden_card_keys or set() + + valid_drag_same: set[int] = set() + valid_drag_mixed: set[int] = set() + if self._dragging and self._press_info: + d_cards: list[SolitaireCard] = self._press_info["cards"] + for t_i in range(10): + if self._press_info.get("col") == t_i: + continue + if self.engine.can_move_to_tableau(d_cards, t_i): + dst_col = self.engine.tableau[t_i] + if dst_col and dst_col[-1].suit == d_cards[0].suit: + valid_drag_same.add(t_i) + else: + valid_drag_mixed.add(t_i) + + hint = self._active_hint + + # 1. Oben links (Spalte 0..1): 5 Nachzieh-Pakete als gestaffelter Fächer + sx0 = self._col_x[0] + stock_hl = ACCENT_GOLD if (hint and hint.get("type") == "deal_stock") else None + vis_packs = [ + p for p in self.engine.stock_deals + if any(self._card_key(c) not in hidden for c in p) + ] + + if not vis_packs: + self._draw_slot(sx0, self._top_y, symbol="—", symbol_color=SUBTLE_BORDER) + self._stock_bbox = (sx0, self._top_y, sx0 + cw, self._top_y + ch) + else: + can_deal_now, deal_reason = self.engine.check_can_deal_row() + for slot_i in range(len(vis_packs)): + px = self._stock_pack_x(slot_i) + is_top_pack = slot_i == len(vis_packs) - 1 + 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) + + last_px = self._stock_pack_x(len(vis_packs) - 1) + self._stock_bbox = (sx0, self._top_y, last_px + cw, self._top_y + ch) + self.canvas.create_text( + last_px + cw - max(5, cw // 15), + self._top_y + ch - max(5, ch // 18), + text=f"×{len(vis_packs)}", + anchor="se", + font=("Helvetica", max(8, cw // 11), "bold"), + fill=ERROR_FG if (not can_deal_now) else ACCENT_GOLD, + ) + + # 2. Oben rechts (Spalten 2..9): 8 Ablage-Slots für vollendete König-bis-Ass-Sequenzen + for r_slot in range(8): + rx = self._col_x[2 + r_slot] + self._draw_slot(rx, self._top_y, symbol="♠", symbol_color=SUBTLE_BORDER) + if r_slot < len(self.engine.completed_runs): + 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: + # König (Index 0 der Sequenz) thront repräsentativ oben auf dem fertigen Stapel + self._draw_card_at(vis_run[0], rx, self._top_y, highlight_color=ACCENT_GOLD) + + # 3. Untere Reihe: 10 Tableau-Spalten + self._tableau_card_rects = [[] for _ in range(10)] + need_fill_warning = bool(self.engine.stock_deals) and self.engine.has_empty_column() + + for col_idx in range(10): + tx = self._col_x[col_idx] + full_col = list(self.engine.tableau[col_idx]) + if exclude_source and exclude_source.get("zone") == "tableau" and exclude_source.get("col") == col_idx: + full_col = full_col[: exclude_source["idx"]] + cards = [c for c in full_col if self._card_key(c) not in hidden] + + slot_hl = None + if not cards: + if col_idx in valid_drag_mixed: + slot_hl = ACCENT_GOTH + elif hint and hint.get("dst_col") == col_idx: + slot_hl = ACCENT_GOLD + elif need_fill_warning and not self._dragging: + slot_hl = SUBTLE_BORDER + self._draw_slot(tx, self._tableau_y, symbol="!" if (not cards and need_fill_warning) else "", highlight_color=slot_hl) + + if not cards: + continue + + movable_from = self.engine.movable_tail_start_index(col_idx) + ys = self._compute_tableau_ys(cards) + + for c_idx, (card, cur_y) in enumerate(zip(cards, ys)): + is_last = c_idx == len(cards) - 1 + c_hl = None + if is_last: + if col_idx in valid_drag_same: + c_hl = ACCENT_GOLD # Gleichfarbiges Ziel glänzt golden! + elif col_idx in valid_drag_mixed: + c_hl = ACCENT_GOTH + if hint: + if hint.get("src_col") == col_idx and c_idx >= hint.get("card_idx", 999): + c_hl = ACCENT_GOLD + 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, + dim_non_movable=(card.face_up and c_idx < movable_from), + ) + 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 nur anzeigen, wenn der Timer bereits aktiv gestartet wurde + if ( + self.engine.has_timer_started + and not self._window_active + and not self.engine.won + and self._modal_overlay is None + ): + bw, bh = 430, 42 + bx = (canvas_w - bw) // 2 + by = canvas_h - bh - 12 + self.canvas.create_rectangle( + bx, by, bx + bw, by + bh, + fill=MODAL_BG, + outline=ACCENT_GOTH, + width=2, + ) + self.canvas.create_text( + bx + bw // 2, + by + bh // 2, + text=t("sol_canvas_paused_banner"), + font=("Helvetica", 10, "bold"), + fill=ACCENT_GOLD, + ) + + self._sync_buttons() + + # ========================================================================= + # Hit-Testing & Maus-Steuerung (Timer startet erst bei echtem Treffer!) + # ========================================================================= + def _hit_test(self, x: int, y: int) -> dict | None: + sx1, sy1, sx2, sy2 = self._stock_bbox + if sx1 <= x <= sx2 and sy1 <= y <= sy2: + return {"zone": "stock"} + + 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: + if not self.engine.can_grab_stack(col_idx, c_idx): + return None + return { + "zone": "tableau", + "col": col_idx, + "idx": c_idx, + "cards": col_cards[c_idx:], + "origin": (x1, y1), + } + + return None + + def _on_mouse_down(self, event): + if self.engine.won or self._modal_overlay is not None: + 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) + self._press_info = hit + + def _on_mouse_move(self, event): + if not self._press_info or self._press_info.get("zone") == "stock": + 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 + 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] * 0.195)) + 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_mouse_up(self, event): + info = self._press_info + was_dragging = self._dragging + self._press_info = None + self._dragging = 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 = ox + (event.x - sx) + drop_y = oy + (event.y - sy) + drag_dy = max(15, int(self.card_size[1] * 0.195)) + + override = { + self._card_key(c): (drop_x, drop_y + i * drag_dy) + for i, c in enumerate(info["cards"]) + } + + prev_runs = len(self.engine.completed_runs) + moved = self._run_animated_action( + lambda: self._try_drop(info, drop_x, drop_y), + override_starts=override, + duration_ms=80, + after_cb=self._after_player_move, + ) + if moved: + self.ctx.sounds.play("deal" if len(self.engine.completed_runs) > prev_runs else "click") + 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 _handle_click(self, info: dict): + if info["zone"] == "stock": + ok, reason = self.engine.check_can_deal_row() + if not ok: + if reason == "empty_column": + self.status_var.set(t("sp_empty_col_deal_err")) + elif reason == "empty_stock": + self.status_var.set(t("sp_no_deals_left_msg")) + self._check_deadlock_and_prompt() + return + + if self._run_animated_action( + self.engine.deal_from_stock, + duration_ms=145, + after_cb=self._after_player_move, + ): + self.ctx.sounds.play("deal") + return + + now = time.monotonic() + 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.engine.won or self._modal_overlay is not None: + 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["zone"] == "stock": + self._handle_click(hit) + else: + self._smart_auto_move(hit) + + def _smart_auto_move(self, info: dict): + """ + Intelligenter Doppelklick / Rechtsklick in Spider Solitaire: + 1. Bevorzugt gleichfarbige Zielkarte (z. B. Pik-7 auf Pik-8) + 2. Sonst passende andersfarbige Zielkarte (z. B. Pik-7 auf Herz-8) + 3. Sonst freie leere Spalte (sofern der Stapel nicht schon ganz alleine auf einer Spalte liegt) + """ + if info.get("zone") != "tableau": + return + src_col = info["col"] + start_idx = info["idx"] + cards: list[SolitaireCard] = info.get("cards", []) + if not cards: + return + + head = cards[0] + prev_runs = len(self.engine.completed_runs) + + def attempt_move() -> bool: + same_suit_targets: list[int] = [] + mixed_suit_targets: list[int] = [] + empty_targets: list[int] = [] + + for dst_col in range(10): + if dst_col == src_col or not self.engine.can_move_to_tableau(cards, dst_col): + continue + dst_pile = self.engine.tableau[dst_col] + if not dst_pile: + if start_idx > 0: # Ganze Spalte in andere leere Spalte schieben vermeiden + empty_targets.append(dst_col) + elif dst_pile[-1].suit == head.suit: + same_suit_targets.append(dst_col) + else: + mixed_suit_targets.append(dst_col) + + for dst_col in same_suit_targets + mixed_suit_targets + empty_targets: + if self.engine.move_tableau_to_tableau(src_col, start_idx, dst_col): + return True + return False + + if self._run_animated_action(attempt_move, duration_ms=120, after_cb=self._after_player_move): + self.ctx.sounds.play("deal" if len(self.engine.completed_runs) > prev_runs else "click") + + def _try_drop(self, info: dict, drop_x: int, drop_y: int) -> bool: + if info.get("zone") != "tableau": + return False + cw, ch = self.card_size + cx = drop_x + cw // 2 + cy = drop_y + ch // 2 + src_col = info["col"] + cards: list[SolitaireCard] = info["cards"] + + best_col: int | None = None + best_dx = 999999 + for col_idx in range(10): + if col_idx == src_col: + continue + tx_center = self._col_x[col_idx] + cw // 2 + dx = abs(cx - tx_center) + if dx <= int(cw * 0.74) and cy >= self._tableau_y - int(ch * 0.35): + if dx < best_dx and self.engine.can_move_to_tableau(cards, col_idx): + best_dx = dx + best_col = col_idx + + if best_col is not None: + return self.engine.move_tableau_to_tableau(src_col, info["idx"], best_col) + return False + + # ========================================================================= + # Aktionen: Undo, Undo All, Deadlock-Check, Aufgeben & Sieg + # ========================================================================= + def _after_player_move(self): + self.status_var.set("") + self._checkpoint_ticks = 0 + self.redraw() + + if self.engine.won: + self._handle_victory() + return + + self._save_progress() + self._check_deadlock_and_prompt() + + def _check_deadlock_and_prompt(self): + if self.engine.won or self._modal_overlay is not None: + 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: + return + self._clear_hint() + + def finish_undo(): + self.status_var.set("") + self._checkpoint_ticks = 0 + self._save_progress() + self.redraw() + + 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: + 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.engine.won or self._modal_overlay is not None: + 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(): + self.redraw() + + def _on_new_or_forfeit_clicked(self): + if self._modal_overlay is not None: + return + if self.animator: + self.animator.flush() + if self.engine.won or self.engine.moves == 0: + self._game_concluded = False + self.engine.new_game(variant_key=self.variant_key, difficulty=self.difficulty) + self._save_progress() + self.status_var.set("") + self.ctx.sounds.play("deal") + self.redraw() + return + self._show_forfeit_modal() + + def _compute_forfeit_penalty(self) -> int: + pid = self.ctx.profile["id"] + prog = Database.get_game_progress(pid, GAME_FOLDER_ID) + win_xp = Progression.calculate_match_xp( + prog["level"], [], "WIN", variant_mult=self._combined_xp_mult + ) + return max(2, int(round(win_xp * SOLO_FORFEIT_XP_RATIO))) + + def _execute_forfeit(self, penalty: int, go_menu: bool): + 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 + 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(), + 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.ctx.refresh_game_progress() + self.ctx.sounds.play("lose") + + if self._modal_overlay is not None: + self._modal_overlay.destroy() + 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._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.ctx.sounds.play("deal") + self.redraw() + + def _show_deadlock_modal(self): + self.engine.pause_timer() + self._save_progress() + penalty = self._compute_forfeit_penalty() + + overlay = tk.Frame( + self.ctx.root, + bg=MODAL_BG, + padx=28, + pady=22, + highlightthickness=2, + highlightbackground=ACCENT_GOTH, + ) + overlay.place(relx=0.5, rely=0.52, anchor="center") + self._modal_overlay = overlay + self._sync_buttons() + + tk.Label( + overlay, + text=t("sol_deadlock_title"), + font=("Georgia", 15, "bold"), + fg=ERROR_FG, + bg=MODAL_BG, + ).pack(pady=(0, 8)) + + tk.Label( + overlay, + text=t("sol_deadlock_desc", penalty), + font=("Helvetica", 10), + fg=FG_COLOR, + bg=MODAL_BG, + wraplength=460, + justify="center", + ).pack(pady=(0, 18)) + + row = tk.Frame(overlay, bg=MODAL_BG) + row.pack() + + def undo_step(): + self._close_active_modal() + self._on_undo() + + def undo_everything(): + self._close_active_modal() + self._on_undo_all() + + ImageButton( + row, + t("sol_deadlock_btn_undo"), + self.ctx.assets.raw_btn, + self.ctx.assets.raw_btn_active, + undo_step, + sound_mgr=self.ctx.sounds, + width=170, + height=36, + font=("Helvetica", 9, "bold"), + enabled=self.engine.can_undo, + ).pack(side="left", padx=5) + + ImageButton( + row, + t("sol_deadlock_btn_undo_all"), + self.ctx.assets.raw_btn, + self.ctx.assets.raw_btn_active, + undo_everything, + sound_mgr=self.ctx.sounds, + width=175, + height=36, + font=("Helvetica", 9, "bold"), + enabled=self.engine.can_undo_all, + ).pack(side="left", padx=5) + + ImageButton( + row, + t("sol_deadlock_btn_end", penalty), + self.ctx.assets.raw_sel, + self.ctx.assets.raw_sel_active, + lambda: self._execute_forfeit(penalty, go_menu=True), + sound_mgr=self.ctx.sounds, + width=165, + height=36, + font=("Helvetica", 9, "bold"), + ).pack(side="left", padx=5) + + def _show_forfeit_modal(self): + self.engine.pause_timer() + self._save_progress() + penalty = self._compute_forfeit_penalty() + overlay = tk.Frame( + self.ctx.root, + bg=MODAL_BG, + padx=28, + pady=22, + highlightthickness=2, + highlightbackground=ERROR_FG, + ) + overlay.place(relx=0.5, rely=0.52, anchor="center") + self._modal_overlay = overlay + self._sync_buttons() + + tk.Label( + overlay, + text=t("sol_forfeit_title"), + font=("Georgia", 15, "bold"), + fg=ERROR_FG, + bg=MODAL_BG, + ).pack(pady=(0, 8)) + + tk.Label( + overlay, + text=t("sol_forfeit_desc", penalty), + font=("Helvetica", 10), + fg=FG_COLOR, + bg=MODAL_BG, + wraplength=430, + justify="center", + ).pack(pady=(0, 18)) + + row = tk.Frame(overlay, bg=MODAL_BG) + row.pack() + + ImageButton( + row, + t("sol_btn_cancel"), + self.ctx.assets.raw_sel, + self.ctx.assets.raw_sel_active, + self._close_active_modal, + sound_mgr=self.ctx.sounds, + width=145, + height=34, + font=("Helvetica", 9, "bold"), + ).pack(side="left", padx=5) + + ImageButton( + row, + t("sol_forfeit_confirm_new"), + self.ctx.assets.raw_btn, + self.ctx.assets.raw_btn_active, + lambda: self._execute_forfeit(penalty, go_menu=False), + sound_mgr=self.ctx.sounds, + width=175, + height=34, + font=("Helvetica", 9, "bold"), + ).pack(side="left", padx=5) + + ImageButton( + row, + t("sol_forfeit_confirm_menu"), + self.ctx.assets.raw_sel, + self.ctx.assets.raw_sel_active, + lambda: self._execute_forfeit(penalty, go_menu=True), + sound_mgr=self.ctx.sounds, + width=175, + height=34, + font=("Helvetica", 9, "bold"), + ).pack(side="left", padx=5) + + def _handle_victory(self): + self._game_concluded = True + pid = self.ctx.profile["id"] + Database.delete_game_state(pid, GAME_FOLDER_ID) + dur = self.engine.get_elapsed_seconds() + + prog = Database.get_game_progress(pid, GAME_FOLDER_ID) + # 104 Karten dauern länger als Klondike -> Speed-Bonus ab <= 6:00 bzw. <= 10:00 Min + speed_bonus = 1.25 if dur <= 360 else (1.12 if dur <= 600 else 1.0) + xp_earned = Progression.calculate_match_xp( + prog["level"], + [], + "WIN", + variant_mult=self._combined_xp_mult * speed_bonus, + ) + + old_lvl, new_lvl = Database.record_game_result( + pid, + variant_key=self.variant_key, + won=True, + duration_sec=dur, + points_gained=xp_earned, + ) + self.ctx.refresh_game_progress() + self.ctx.sounds.play("win") + self._show_victory_modal(xp_earned, old_lvl, new_lvl, dur) + + def _show_victory_modal(self, xp_earned: int, old_lvl: int, new_lvl: int, dur: float): + overlay = tk.Frame( + self.ctx.root, + bg=MODAL_BG, + padx=30, + pady=24, + highlightthickness=2, + highlightbackground=ACCENT_GOLD, + ) + overlay.place(relx=0.5, rely=0.52, anchor="center") + self._modal_overlay = overlay + self._sync_buttons() + + frames = self.ctx.assets.get_gif_frames("win_gif") + if frames: + gif_lbl = tk.Label(overlay, bg=MODAL_BG, image=frames[0]) + gif_lbl.pack(pady=(0, 10)) + + def anim(idx: int = 0): + if not self._canvas_alive() or self._modal_overlay is None: + return + gif_lbl.configure(image=frames[idx % len(frames)]) + self._gif_job = self.ctx.root.after(90, lambda: anim(idx + 1)) + + if len(frames) > 1: + anim(0) + + tk.Label( + overlay, + text=t("sol_win_title"), + font=("Georgia", 16, "bold"), + fg=ACCENT_GOLD, + bg=MODAL_BG, + ).pack(pady=(0, 6)) + + tk.Label( + overlay, + text=t( + "sol_win_summary", + self.engine.score, + self.engine.moves, + Database.format_seconds(dur), + t(f"sol_diff_short_{self.difficulty}"), + ), + font=("Helvetica", 11), + fg=FG_COLOR, + bg=MODAL_BG, + ).pack(pady=(0, 8)) + + tk.Label( + overlay, + text=t("bj_popup_xp_earned", xp_earned), + font=("Helvetica", 11, "bold"), + fg=ACCENT_GOTH, + bg=MODAL_BG, + ).pack(pady=(0, 6)) + + if new_lvl > old_lvl: + tk.Label( + overlay, + text=t("bj_popup_level_up", new_lvl, Progression.get_prestige_title(new_lvl)), + font=("Georgia", 12, "bold"), + fg="#7be08a", + bg=MODAL_BG, + ).pack(pady=(2, 10)) + + btn_row = tk.Frame(overlay, bg=MODAL_BG) + btn_row.pack(pady=(12, 0)) + + def play_again(): + if self._gif_job is not None: + try: + self.ctx.root.after_cancel(self._gif_job) + except Exception: + pass + self._gif_job = None + overlay.destroy() + self._modal_overlay = None + 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("") + self.ctx.sounds.play("deal") + self.redraw() + + def to_menu(): + self._cleanup_timers() + if callable(self.on_back_to_menu): + self.on_back_to_menu() + + ImageButton( + btn_row, + t("sol_play_again_btn"), + self.ctx.assets.raw_btn, + self.ctx.assets.raw_btn_active, + play_again, + sound_mgr=self.ctx.sounds, + width=175, + height=36, + font=("Helvetica", 10, "bold"), + ).pack(side="left", padx=6) + + ImageButton( + btn_row, + t("bj_popup_to_menu_btn"), + self.ctx.assets.raw_sel, + self.ctx.assets.raw_sel_active, + to_menu, + sound_mgr=self.ctx.sounds, + width=175, + height=36, + font=("Helvetica", 9 if len(t("bj_popup_to_menu_btn")) > 18 else 10, "bold"), + ).pack(side="left", padx=6) \ No newline at end of file diff --git a/models/__pycache__/resource_manager.cpython-311.pyc b/models/__pycache__/resource_manager.cpython-311.pyc index f2c9e8e..e730626 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 ad5fd96..fa99321 100644 --- a/models/resource_manager.py +++ b/models/resource_manager.py @@ -1,6 +1,12 @@ # -*- coding: utf-8 -*- from pathlib import Path -from resources.code_res.game_constants import CARD_BACK_PATTERN, DEFAULT_CARD_THEME, UI_IMAGES +from resources.code_res.game_constants import ( + CARD_BACK_PATTERN, + DEFAULT_CARD_THEME, + GAME_ICON_MAP, + GAME_ICONS_SUBDIR, + UI_IMAGES, +) class ResourceManager: @@ -8,6 +14,7 @@ class ResourceManager: self.root_dir = root_dir self.res_dir = root_dir / "resources" self.images_dir = self.res_dir / "images" + 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" self.ambiance_dir = self.sounds_dir / "ambiance" @@ -26,4 +33,11 @@ class ResourceManager: def get_ui_image_path(self, key_or_filename: str) -> Path: filename = UI_IMAGES.get(key_or_filename, key_or_filename) - return self.images_dir / filename \ No newline at end of file + return self.images_dir / filename + + def get_game_icon_path(self, game_folder: str) -> Path | None: + icon_file = GAME_ICON_MAP.get(game_folder) + if not icon_file: + return None + p = self.game_icons_dir / icon_file + return p if p.is_file() else None \ No newline at end of file diff --git a/resources/code_res/__pycache__/game_constants.cpython-311.pyc b/resources/code_res/__pycache__/game_constants.cpython-311.pyc index 23ce520..e775226 100644 Binary files a/resources/code_res/__pycache__/game_constants.cpython-311.pyc and b/resources/code_res/__pycache__/game_constants.cpython-311.pyc differ diff --git a/resources/code_res/game_constants.py b/resources/code_res/game_constants.py index 4d27f63..63ac7df 100644 --- a/resources/code_res/game_constants.py +++ b/resources/code_res/game_constants.py @@ -11,6 +11,7 @@ DEFAULT_CARD_THEME = "default" UI_IMAGES = { "background": "background.jpeg", "title": "title.jpg", + "general_table": "general_table.jpg", "btn_normal": "button1.png", "btn_active": "button1_active.png", "sel_inactive": "selection_inactive.png", @@ -21,6 +22,18 @@ UI_IMAGES = { } APP_ICON_REL_PATH = "resources/images/game_icon.ico" +GAME_ICONS_SUBDIR = "game_icons" + +GAME_ICON_MAP = { + "blackjack": "blackjack_icon.ico", + "poker": "poker_icon.ico", + "solitaire/klondike": "klondike_icon.ico", + "solitaire/freecell": "freecell_icon.ico", + "solitaire/spider_solitaire": "spider_icon.ico", + "romme": "romme_icon.ico", + "party/romme": "romme_icon.ico", +} + FONTS_REL_DIR = "resources/fonts" CUSTOM_FONT_FILES = ( "OldLondon.ttf", @@ -218,7 +231,7 @@ KLONDIKE_VARIANTS = { }, } -# --- Freecell --- +# --- FreeCell --- FREECELL_VARIANTS = { "freecell_std": { "xp_mult": 1.15, @@ -226,6 +239,28 @@ FREECELL_VARIANTS = { }, } +# --- Spider Solitaire --- +SPIDER_VARIANTS = { + "spider_1suit": { + "num_suits": 1, + "suits": ("S",), + "xp_mult": 1.10, + "back_color": "Black", + }, + "spider_2suit": { + "num_suits": 2, + "suits": ("S", "H"), + "xp_mult": 1.45, + "back_color": "Black", + }, + "spider_4suit": { + "num_suits": 4, + "suits": ("C", "D", "H", "S"), + "xp_mult": 1.95, + "back_color": "Black", + }, +} + # --- UI Theme & Geometrie --- DEFAULT_WINDOW_GEOM = "1150x800" MIN_WINDOW_SIZE = (980, 700) diff --git a/resources/code_res/internal_base.db b/resources/code_res/internal_base.db index fe2ed42..9bf703d 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/internal_base.sql b/resources/code_res/internal_base.sql index 6061481..e3613a3 100644 --- a/resources/code_res/internal_base.sql +++ b/resources/code_res/internal_base.sql @@ -1060,4 +1060,35 @@ INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES ('fc_hud_capacity', 'DE', ' | Max. Stapel: {0}'), ('fc_hud_capacity', 'EN', ' | Max Move: {0}'); +INSERT OR REPLACE INTO base_i18n (key, lang, val) VALUES +-- ========================================================================= +-- DE & EN: SPIDER SOLITAIRE +-- ========================================================================= +('sp_menu_topbar', 'DE', 'Spider Solitaire – Farben & Schwierigkeit'), +('sp_menu_topbar', 'EN', 'Spider Solitaire – Suits & Difficulty'), +('sp_menu_subtitle', 'DE', '104 Karten auf 10 Spalten — bilde 8 komplette Farb-Sequenzen von König bis Ass!'), +('sp_menu_subtitle', 'EN', '104 cards across 10 columns — assemble 8 complete same-suit runs from King to Ace!'), +('sp_suit_mode_lbl', 'DE', 'Farben-Modus:'), +('sp_suit_mode_lbl', 'EN', 'Suit Mode:'), +('sp_suit_toggle_1', 'DE', '1 Farbe (Pik)'), +('sp_suit_toggle_1', 'EN', '1 Suit (Spades)'), +('sp_suit_toggle_2', 'DE', '2 Farben (♠ / ♥)'), +('sp_suit_toggle_2', 'EN', '2 Suits (♠ / ♥)'), +('sp_suit_toggle_4', 'DE', '4 Farben (Alle)'), +('sp_suit_toggle_4', 'EN', '4 Suits (All)'), +('sp_desc_spider_1suit', 'DE', 'Nur Pik (♠) • Jede absteigende Reihe ist verschiebbar • Basis-XP: x1.10'), +('sp_desc_spider_1suit', 'EN', 'Spades only (♠) • Every descending run moves together • Base XP: x1.10'), +('sp_desc_spider_2suit', 'DE', 'Pik & Herz (♠/♥) • Taktischer Mix aus Tempo & Farb-Disziplin • Basis-XP: x1.45'), +('sp_desc_spider_2suit', 'EN', 'Spades & Hearts (♠/♥) • Tactical blend of flow & suit discipline • Base XP: x1.45'), +('sp_desc_spider_4suit', 'DE', 'Alle 4 Farben • Die Königsdisziplin des Solitaire • Basis-XP: x1.95'), +('sp_desc_spider_4suit', 'EN', 'All 4 Suits • The supreme Solitaire challenge • Base XP: x1.95'), +('sp_controls_hint', 'DE', 'Maus: Ziehen & Ablegen • Doppelklick/Rechtsklick: Gleichfarbig bevorzugt • Stapel oben links: +10 Karten • Strg+Z: Rückgängig'), +('sp_controls_hint', 'EN', 'Mouse: Drag & Drop • Double/Right-Click: Prefers same-suit • Top-left Stock: Deal 10 • Ctrl+Z: Undo'), +('sp_empty_col_deal_err', 'DE', 'Strenge Regel: Alle 10 Spalten müssen besetzt sein, bevor neu gegeben werden darf!'), +('sp_empty_col_deal_err', 'EN', 'Strict Rule: Every column must contain at least 1 card before dealing a new row!'), +('sp_no_deals_left_msg', 'DE', 'Keine Nachzieh-Pakete mehr übrig!'), +('sp_no_deals_left_msg', 'EN', 'No stock deals remaining!'), +('sp_hud_extra', 'DE', ' | Sequenzen: {0}/8 | Pakete: {1}/5'), +('sp_hud_extra', 'EN', ' | Runs: {0}/8 | Deals: {1}/5'); + COMMIT; \ No newline at end of file diff --git a/resources/images/game_icons/blackjack_icon.ico b/resources/images/game_icons/blackjack_icon.ico new file mode 100644 index 0000000..225a58f Binary files /dev/null and b/resources/images/game_icons/blackjack_icon.ico differ diff --git a/resources/images/game_icons/freecell_icon.ico b/resources/images/game_icons/freecell_icon.ico new file mode 100644 index 0000000..79f8fef Binary files /dev/null and b/resources/images/game_icons/freecell_icon.ico differ diff --git a/resources/images/game_icons/klondike_icon.ico b/resources/images/game_icons/klondike_icon.ico new file mode 100644 index 0000000..ea96402 Binary files /dev/null and b/resources/images/game_icons/klondike_icon.ico differ diff --git a/resources/images/game_icons/poker_icon.ico b/resources/images/game_icons/poker_icon.ico new file mode 100644 index 0000000..18e98c0 Binary files /dev/null and b/resources/images/game_icons/poker_icon.ico differ diff --git a/resources/images/game_icons/romme_icon.ico b/resources/images/game_icons/romme_icon.ico new file mode 100644 index 0000000..fc88caf Binary files /dev/null and b/resources/images/game_icons/romme_icon.ico differ diff --git a/resources/images/game_icons/spider_icon.ico b/resources/images/game_icons/spider_icon.ico new file mode 100644 index 0000000..a7eb670 Binary files /dev/null and b/resources/images/game_icons/spider_icon.ico differ diff --git a/user_data.db b/user_data.db index 13efc3e..cab3d7b 100644 Binary files a/user_data.db and b/user_data.db differ diff --git a/view/menus/__pycache__/main_menu_view.cpython-311.pyc b/view/menus/__pycache__/main_menu_view.cpython-311.pyc index 0735d5e..87d2cdd 100644 Binary files a/view/menus/__pycache__/main_menu_view.cpython-311.pyc and b/view/menus/__pycache__/main_menu_view.cpython-311.pyc differ diff --git a/view/menus/main_menu_view.py b/view/menus/main_menu_view.py index 0060cbd..bb03533 100644 --- a/view/menus/main_menu_view.py +++ b/view/menus/main_menu_view.py @@ -2,6 +2,7 @@ # view/menus/main_menu_view.py import tkinter as tk +from games.solitaire.base.solitaire_theme import get_game_icon_photo from models.database import Database from resources.code_res.game_constants import ( ACCENT_GOLD, ACCENT_GOTH, BG_COLOR, BORDER_COLOR, CAT_LUCK, @@ -20,6 +21,7 @@ class MainMenuView: self.assets = root_view.assets self.sounds = root_view.ctrl.sounds self.selected_category: str = CAT_LUCK + self._card_icon_refs: list = [] def show( self, @@ -29,6 +31,7 @@ class MainMenuView: category: str | None = None, ): self.root.clear_window(apply_global_bg=True) + self._card_icon_refs.clear() valid_cats = {c[0] for c in GAME_CATEGORIES} if category in valid_cats: @@ -76,7 +79,6 @@ class MainMenuView: sound_mgr=self.sounds, width=85, height=36, font=("Helvetica", 9, "bold") ).pack(side="left") - # Mitte: Proportionales Titel-Banner (320px breit -> ~80px hoch) header_banner = self.assets.get_proportional_photo("title_main_header", self.assets.raw_title, 320) if header_banner: hdr_lbl = tk.Label( @@ -121,8 +123,15 @@ class MainMenuView: font=("Helvetica", 11), fg=MUTED_FG, bg=PANEL_BG, wraplength=520, justify="center" ).pack(pady=(0, 22)) + locked_folder = self.ctrl.get_locked_devils_game_folder() or "" resume_card = self._create_game_card( - pakt_panel, t("devils_deal_resume_card"), "", self.ctrl.resume_devils_deal, bg_col=PANEL_BG + pakt_panel, + t("devils_deal_resume_card"), + "", + self.ctrl.resume_devils_deal, + game_folder=locked_folder, + bg_col=PANEL_BG, + is_online=True, ) resume_card.pack() return @@ -193,12 +202,20 @@ class MainMenuView: game["title"], sub_txt, lambda g=game: self.ctrl.launch_game(g), + game_folder=game.get("folder", ""), is_online=is_online_tab, ) card_widget.grid(row=idx // 4, column=idx % 4, padx=18, pady=10) def _create_game_card( - self, parent, game_title: str, rank_subtitle: str, on_click, bg_col: str = BG_COLOR, is_online: bool = False + self, + parent, + game_title: str, + rank_subtitle: str, + on_click, + game_folder: str = "", + bg_col: str = BG_COLOR, + is_online: bool = False, ) -> tk.Canvas: card_w, card_h = MENU_CARD_SIZE cv = tk.Canvas(parent, width=card_w, height=card_h, bg=bg_col, highlightthickness=0, cursor="hand2") @@ -211,41 +228,79 @@ class MainMenuView: fill=PANEL_BG, outline=base_outline, width=2 ) inner_id = cv.create_rectangle( - 12, 12, card_w - 12, card_h - 12, + 11, 11, card_w - 11, card_h - 11, fill="#16131c", outline=SUBTLE_BORDER, width=1 ) - # "Helvetica" für Unicode-Ornamente (❖), damit OldLondon kein Kästchen zeichnet - top_gem = cv.create_text(card_w // 2, 28, text="†" if is_online else "❖", font=("Helvetica", 11, "bold"), fill=gem_color) - bot_gem = cv.create_text(card_w // 2, card_h - 28, text="†" if is_online else "❖", font=("Helvetica", 11, "bold"), fill=gem_color) + + icon_photo = get_game_icon_photo(self.assets.res, game_folder, size_px=92) if game_folder else None + top_gem = None + bot_gem = None longest_word = max((len(w) for w in game_title.replace("\n", " ").split()), default=0) - title_size = 15 if longest_word >= 11 else 17 - title_y = (card_h // 2 - 22) if rank_subtitle else (card_h // 2) - txt_id = cv.create_text( - card_w // 2, title_y, - text=game_title, width=card_w - 32, justify="center", - font=("Georgia", title_size, "bold"), fill=FG_COLOR - ) + if icon_photo is not None: + self._card_icon_refs.append(icon_photo) + # Dezenter Sockel-Schein hinter dem Spiel-Icon + icon_glow_id = cv.create_rectangle( + card_w // 2 - 48, 22, card_w // 2 + 48, 118, + outline=SUBTLE_BORDER, width=1 + ) + cv.create_image(card_w // 2, 70, image=icon_photo, anchor="center") - sub_id = None - if rank_subtitle: - cv.create_line( - 36, card_h // 2 + 4, card_w - 36, card_h // 2 + 4, - fill=SUBTLE_BORDER, width=1 + title_size = 13 if longest_word >= 10 else 15 + title_y = 146 if rank_subtitle else 166 + txt_id = cv.create_text( + card_w // 2, title_y, + text=game_title, width=card_w - 28, justify="center", + font=("Georgia", title_size, "bold"), fill=FG_COLOR ) - sub_id = cv.create_text( - card_w // 2, card_h // 2 + 34, - text=rank_subtitle, width=card_w - 30, justify="center", - font=("Helvetica", 9, "bold"), fill=gem_color + + sub_id = None + if rank_subtitle: + cv.create_line( + 30, 174, card_w - 30, 174, + fill=SUBTLE_BORDER, width=1 + ) + sub_id = cv.create_text( + card_w // 2, 203, + text=rank_subtitle, width=card_w - 26, justify="center", + font=("Helvetica", 9, "bold"), fill=gem_color + ) + else: + icon_glow_id = None + top_gem = cv.create_text(card_w // 2, 28, text="†" if is_online else "❖", font=("Helvetica", 11, "bold"), fill=gem_color) + bot_gem = cv.create_text(card_w // 2, card_h - 28, text="†" if is_online else "❖", font=("Helvetica", 11, "bold"), fill=gem_color) + + title_size = 15 if longest_word >= 11 else 17 + title_y = (card_h // 2 - 22) if rank_subtitle else (card_h // 2) + txt_id = cv.create_text( + card_w // 2, title_y, + text=game_title, width=card_w - 32, justify="center", + font=("Georgia", title_size, "bold"), fill=FG_COLOR ) + sub_id = None + if rank_subtitle: + cv.create_line( + 36, card_h // 2 + 4, card_w - 36, card_h // 2 + 4, + fill=SUBTLE_BORDER, width=1 + ) + sub_id = cv.create_text( + card_w // 2, card_h // 2 + 34, + text=rank_subtitle, width=card_w - 30, justify="center", + font=("Helvetica", 9, "bold"), fill=gem_color + ) + def _on_enter(_e): cv.itemconfigure(outer_id, outline=ACCENT_GOLD) cv.itemconfigure(inner_id, fill="#211c2a", outline=gem_color) cv.itemconfigure(txt_id, fill=ACCENT_GOLD) - cv.itemconfigure(top_gem, fill=ACCENT_GOLD) - cv.itemconfigure(bot_gem, fill=ACCENT_GOLD) + if icon_glow_id: + cv.itemconfigure(icon_glow_id, outline=ACCENT_GOLD) + if top_gem: + cv.itemconfigure(top_gem, fill=ACCENT_GOLD) + if bot_gem: + cv.itemconfigure(bot_gem, fill=ACCENT_GOLD) if sub_id: cv.itemconfigure(sub_id, fill="#ffffff") @@ -253,12 +308,16 @@ class MainMenuView: cv.itemconfigure(outer_id, outline=base_outline) cv.itemconfigure(inner_id, fill="#16131c", outline=SUBTLE_BORDER) cv.itemconfigure(txt_id, fill=FG_COLOR) - cv.itemconfigure(top_gem, fill=gem_color) - cv.itemconfigure(bot_gem, fill=gem_color) + if icon_glow_id: + cv.itemconfigure(icon_glow_id, outline=SUBTLE_BORDER) + if top_gem: + cv.itemconfigure(top_gem, fill=gem_color) + if bot_gem: + cv.itemconfigure(bot_gem, fill=gem_color) if sub_id: cv.itemconfigure(sub_id, fill=gem_color) cv.bind("", _on_enter) cv.bind("", _on_leave) - cv.bind("", lambda e: (self.sounds.play("click"), on_click())) + cv.bind("", lambda _e: (self.sounds.play("click"), on_click())) return cv \ No newline at end of file