# -*- coding: utf-8 -*- # games/solitaire/klondike/models/klondike_engine.py from __future__ import annotations from games.solitaire.base.solitaire_core import ( SolitaireBaseEngine, SolitaireCard, is_alternating_descending, ) from games.solitaire.klondike.models.klondike_hint_analyzer import KlondikeHintAnalyzer from games.solitaire.klondike.models.klondike_solver import generate_solvable_klondike_deck from resources.code_res.game_constants import SOLITAIRE_DIFFICULTIES, SUITS class KlondikeEngine(SolitaireBaseEngine): """Klondike-Spiellogik (Draw 1 & Draw 3) mit garantierter Lösbarkeit & Stagnationssperre.""" NUM_TABLEAU = 7 NUM_FOUNDATIONS = 4 MAX_STAGNANT_CYCLES = 3 SCORE_WASTE_TO_TABLEAU = 5 SCORE_TO_FOUNDATION = 10 SCORE_FLIP_TABLEAU = 5 SCORE_FOUNDATION_TO_TABLEAU = -15 SCORE_RECYCLE_DRAW1 = -100 SCORE_RECYCLE_DRAW3 = -20 def __init__(self, draw_count: int = 1, difficulty: int = 1, seed: int | None = None): super().__init__() self.draw_count: int = 3 if draw_count >= 3 else 1 self.difficulty: int = max(0, min(3, int(difficulty))) self.seed: int | None = seed self.redeals_used: int = 0 self.redeal_limit: int | None = None self.stagnant_cycles: int = 0 self.progress_in_current_cycle: bool = False self.stock: list[SolitaireCard] = [] self.waste: list[SolitaireCard] = [] self.foundations: list[list[SolitaireCard]] = [[] for _ in range(self.NUM_FOUNDATIONS)] self.tableau: list[list[SolitaireCard]] = [[] for _ in range(self.NUM_TABLEAU)] self.new_game(draw_count=self.draw_count, difficulty=self.difficulty, seed=seed) def new_game( self, draw_count: int | None = None, difficulty: int | None = None, seed: int | None = None, ): if draw_count is not None: self.draw_count = 3 if draw_count >= 3 else 1 if difficulty is not None: self.difficulty = max(0, min(3, int(difficulty))) self.seed = seed self.redeals_used = 0 self.stagnant_cycles = 0 self.progress_in_current_cycle = False diff_cfg = SOLITAIRE_DIFFICULTIES.get(self.difficulty, SOLITAIRE_DIFFICULTIES[1]) self.redeal_limit = diff_cfg["redeal_limit_d3"] if self.draw_count == 3 else None self.reset_tracking() deck = generate_solvable_klondike_deck( draw_count=self.draw_count, difficulty=self.difficulty, redeal_limit=self.redeal_limit, seed=seed, ) self.foundations = [[] for _ in range(self.NUM_FOUNDATIONS)] self.tableau = [[] for _ in range(self.NUM_TABLEAU)] self.waste = [] cursor = 0 for col_idx in range(self.NUM_TABLEAU): col_cards = deck[cursor : cursor + col_idx + 1] cursor += col_idx + 1 for c in col_cards: c.face_up = False col_cards[-1].face_up = True self.tableau[col_idx] = col_cards self.stock = deck[cursor:] for c in self.stock: c.face_up = False self.capture_initial_state() def _mark_board_progress(self): self.stagnant_cycles = 0 self.progress_in_current_cycle = True def _add_score(self, delta: int): self.score = max(0, self.score + delta) def _check_victory(self) -> bool: if sum(len(f) for f in self.foundations) == 52: self.mark_won() return True return False def _reveal_top_if_needed(self, col_idx: int) -> bool: col = self.tableau[col_idx] if col and not col[-1].face_up: col[-1].face_up = True self._add_score(self.SCORE_FLIP_TABLEAU) return True return False def foundation_index_for_suit(self, suit: str) -> int: return SUITS.index(suit) def can_move_to_foundation(self, card: SolitaireCard, found_idx: int) -> bool: if not card.face_up or not (0 <= found_idx < self.NUM_FOUNDATIONS): return False if card.suit != SUITS[found_idx]: return False pile = self.foundations[found_idx] return (card.value == 1) if not pile else (card.value == pile[-1].value + 1) def can_move_to_tableau(self, moving_cards: list[SolitaireCard], dst_col: int) -> bool: if not moving_cards or not (0 <= dst_col < self.NUM_TABLEAU): return False if not is_alternating_descending(moving_cards): return False head = moving_cards[0] dst = self.tableau[dst_col] if not dst: return head.value == 13 top = dst[-1] return top.face_up and (top.is_red != head.is_red) and (top.value == head.value + 1) def is_stagnation_locked(self) -> bool: return ( not self.stock and bool(self.waste) and self.stagnant_cycles >= self.MAX_STAGNANT_CYCLES ) def is_redeal_exhausted(self) -> bool: return ( not self.stock and bool(self.waste) and self.redeal_limit is not None and self.redeals_used >= self.redeal_limit ) def is_stock_locked(self) -> bool: return self.is_stagnation_locked() or self.is_redeal_exhausted() def can_draw_or_recycle(self) -> bool: return bool(self.stock) or (bool(self.waste) and not self.is_stock_locked()) def draw_from_stock(self) -> bool: if self.won: return False if self.stock: self.push_undo() count = min(self.draw_count, len(self.stock)) for _ in range(count): card = self.stock.pop() card.face_up = True self.waste.append(card) self.moves += 1 if not self.stock and not self.progress_in_current_cycle: self.stagnant_cycles += 1 return True if self.waste and not self.is_stock_locked(): self.push_undo() while self.waste: card = self.waste.pop() card.face_up = False self.stock.append(card) self.redeals_used += 1 self.progress_in_current_cycle = False self.moves += 1 if self.draw_count == 1: self._add_score(self.SCORE_RECYCLE_DRAW1) elif self.redeals_used > 3: self._add_score(self.SCORE_RECYCLE_DRAW3) return True return False def move_waste_to_foundation(self, found_idx: int | None = None) -> bool: if self.won or not self.waste: return False card = self.waste[-1] target_idx = self.foundation_index_for_suit(card.suit) if found_idx is None else found_idx if not self.can_move_to_foundation(card, target_idx): return False self.push_undo() self.waste.pop() self.foundations[target_idx].append(card) self.moves += 1 self._mark_board_progress() self._add_score(self.SCORE_TO_FOUNDATION) self._check_victory() return True def move_waste_to_tableau(self, dst_col: int) -> bool: if self.won or not self.waste: return False card = self.waste[-1] if not self.can_move_to_tableau([card], dst_col): return False self.push_undo() self.waste.pop() self.tableau[dst_col].append(card) self.moves += 1 self._mark_board_progress() self._add_score(self.SCORE_WASTE_TO_TABLEAU) return True def move_tableau_to_foundation(self, src_col: int, found_idx: int | None = None) -> bool: if self.won or not (0 <= src_col < self.NUM_TABLEAU) or not self.tableau[src_col]: return False card = self.tableau[src_col][-1] target_idx = self.foundation_index_for_suit(card.suit) if found_idx is None else found_idx if not self.can_move_to_foundation(card, target_idx): return False self.push_undo() self.tableau[src_col].pop() self.foundations[target_idx].append(card) self.moves += 1 self._mark_board_progress() self._add_score(self.SCORE_TO_FOUNDATION) self._reveal_top_if_needed(src_col) self._check_victory() return True def move_tableau_to_tableau(self, src_col: int, start_card_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 src_pile = self.tableau[src_col] if not (0 <= start_card_idx < len(src_pile)): return False moving = src_pile[start_card_idx:] if not self.can_move_to_tableau(moving, dst_col): return False self.push_undo() del src_pile[start_card_idx:] self.tableau[dst_col].extend(moving) self.moves += 1 self._mark_board_progress() self._reveal_top_if_needed(src_col) return True def move_foundation_to_tableau(self, found_idx: int, dst_col: int) -> bool: if self.won or not (0 <= found_idx < self.NUM_FOUNDATIONS): return False f_pile = self.foundations[found_idx] if not f_pile or not self.can_move_to_tableau([f_pile[-1]], dst_col): return False self.push_undo() card = f_pile.pop() self.tableau[dst_col].append(card) self.moves += 1 self._mark_board_progress() self._add_score(self.SCORE_FOUNDATION_TO_TABLEAU) return True def can_auto_complete(self) -> bool: if self.won or self.stock or self.waste: return False return all(card.face_up for col in self.tableau for card in col) def auto_complete_step(self, record_undo: bool = False) -> tuple[int, int] | None: if self.won: return None candidates: list[tuple[int, int, int]] = [] for col_idx, col in enumerate(self.tableau): if not col: continue card = col[-1] f_idx = self.foundation_index_for_suit(card.suit) if self.can_move_to_foundation(card, f_idx): candidates.append((card.value, col_idx, f_idx)) if not candidates: return None candidates.sort(key=lambda item: item[0]) _, best_col, best_f_idx = candidates[0] if record_undo: self.push_undo() card = self.tableau[best_col].pop() self.foundations[best_f_idx].append(card) self.moves += 1 self._mark_board_progress() self._add_score(self.SCORE_TO_FOUNDATION) self._reveal_top_if_needed(best_col) self._check_victory() return best_col, best_f_idx def has_any_meaningful_move(self) -> bool: return KlondikeHintAnalyzer.has_any_meaningful_move(self) def get_hint(self) -> dict | None: return KlondikeHintAnalyzer.get_hint(self) def serialize_board(self) -> dict: return { "draw_count": self.draw_count, "difficulty": self.difficulty, "redeals_used": self.redeals_used, "redeal_limit": self.redeal_limit, "stagnant_cycles": self.stagnant_cycles, "progress_in_cycle": 1 if self.progress_in_current_cycle else 0, "stock": [c.to_dict() for c in self.stock], "waste": [c.to_dict() for c in self.waste], "foundations": [[c.to_dict() for c in f] for f in self.foundations], "tableau": [[c.to_dict() for c in col] for col in self.tableau], } def restore_board(self, board: dict): self.draw_count = int(board.get("draw_count", 1)) self.difficulty = max(0, min(3, int(board.get("difficulty", 1)))) self.redeals_used = int(board.get("redeals_used", 0)) raw_lim = board.get("redeal_limit", None) self.redeal_limit = int(raw_lim) if raw_lim is not None else None self.stagnant_cycles = int(board.get("stagnant_cycles", 0)) self.progress_in_current_cycle = bool(board.get("progress_in_cycle", 0)) self.stock = [SolitaireCard.from_dict(d) for d in board["stock"]] self.waste = [SolitaireCard.from_dict(d) for d in board["waste"]] self.foundations = [[SolitaireCard.from_dict(d) for d in f] for f in board["foundations"]] self.tableau = [[SolitaireCard.from_dict(d) for d in col] for col in board["tableau"]]