# -*- 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_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 - 3-Zyklen-Stagnationssperre auf dem Stock (rotes X, per Undo auflösbar) - automatischer Sackgassen-Erkennung (has_any_meaningful_move) """ 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 # Zählt volle Stock-Durchläufe ohne jeglichen Spielfortschritt 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): """Sobald eine Karte auf dem Spielfeld bewegt wird, wird der Stagnationszähler zurückgesetzt.""" 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 # --- Regel-Prüfungen --- 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 target_suit = SUITS[found_idx] if card.suit != target_suit: return False pile = self.foundations[found_idx] if not pile: return card.value == 1 return 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) # --- Stock, Redeal-Limit & 3-Zyklen-Stagnationssperre --- def is_stagnation_locked(self) -> bool: """True, wenn 3 volle Durchläufe des Decks ohne jede Änderung erfolgt sind.""" 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: """True, wenn der Stapel nicht mehr neu umgedreht werden darf (Rotes X).""" return self.is_stagnation_locked() or self.is_redeal_exhausted() def can_draw_or_recycle(self) -> bool: if self.stock: return True if self.waste and not self.is_stock_locked(): return True return False 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 # Wenn gerade die letzte Karte eines kompletten ereignislosen Durchlaufs aufgedeckt wurde, # zählt dieser Zyklus als abgeschlossen -> beim 3. Mal erscheint sofort das rote X! 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 # --- Aktionen: Kartenverschiebungen --- 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: return False card = f_pile[-1] if not self.can_move_to_tableau([card], dst_col): return False self.push_undo() 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 # --- Komfort: Auto-Complete, Hinweise & Sackgassen-Prüfung --- 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 _card_can_play_anywhere(self, card: SolitaireCard) -> bool: probe = SolitaireCard(suit=card.suit, rank=card.rank, face_up=True, deck_id=card.deck_id) if self.can_move_to_foundation(probe, self.foundation_index_for_suit(probe.suit)): return True return any(self.can_move_to_tableau([probe], dst_col) for dst_col in range(self.NUM_TABLEAU)) def _reachable_stock_waste_cards(self) -> list[SolitaireCard]: """Ermittelt alle Karten, die durch Ziehen/Recyclen aktuell noch oben auf dem Waste landen können.""" reachable: list[SolitaireCard] = [] if self.waste: reachable.append(self.waste[-1]) # 1. Restlichen aktuellen Stock in draw_count-Schritten simulieren if self.stock: sim_stk = list(self.stock) while sim_stk: step = min(self.draw_count, len(sim_stk)) top_drawn = None for _ in range(step): top_drawn = sim_stk.pop() if top_drawn is not None: reachable.append(top_drawn) # 2. Falls danach noch ein Recycle erlaubt wäre, auch den nächsten Zyklus prüfen will_lock_after_stock = ( bool(self.stock) and (not self.progress_in_current_cycle) and (self.stagnant_cycles + 1 >= self.MAX_STAGNANT_CYCLES) ) can_recycle_next = ( not self.is_stock_locked() and not will_lock_after_stock and (self.redeal_limit is None or self.redeals_used < self.redeal_limit) ) if can_recycle_next and (self.stock or self.waste): full_cycle = list(self.waste) + list(reversed(self.stock)) sim_stk2 = list(reversed(full_cycle)) while sim_stk2: step = min(self.draw_count, len(sim_stk2)) top_drawn = None for _ in range(step): top_drawn = sim_stk2.pop() if top_drawn is not None: reachable.append(top_drawn) return reachable def has_any_meaningful_move(self) -> bool: """ Prüft, ob noch irgendein sinnvoller Zug existiert. Reine Endlos-Züge (König von leerer Spalte zu leerer Spalte, grundloses Hin-und-Her-Schieben von Teil-Runs ohne Freilegung einer verdeckten oder Foundation-fähigen Karte) zählen NICHT. """ if self.won: return True # 1. Tableau-Spitze -> Foundation for col_idx, col in enumerate(self.tableau): if col: top = col[-1] if self.can_move_to_foundation(top, self.foundation_index_for_suit(top.suit)): return True # 2. Sinnvolle Tableau -> Tableau Züge for src_col, col in enumerate(self.tableau): if not col: continue first_up = next((i for i, c in enumerate(col) if c.face_up), len(col)) if first_up >= len(col): continue # a) Ganzen offenen Stapel bewegen (legt verdeckte Karte frei oder räumt Spalte für anderen König) whole_run = col[first_up:] if not (first_up == 0 and whole_run[0].value == 13): for dst_col in range(self.NUM_TABLEAU): if src_col != dst_col and self.can_move_to_tableau(whole_run, dst_col): # Leert es nur eine Spalte (first_up == 0, Karte != K), ist das immer produktiv return True # b) Teil-Run splitten, falls die freigelegte Karte darunter direkt auf die Foundation passt for split_idx in range(first_up + 1, len(col)): exposed = col[split_idx - 1] if self.can_move_to_foundation(exposed, self.foundation_index_for_suit(exposed.suit)): sub_run = col[split_idx:] for dst_col in range(self.NUM_TABLEAU): if src_col != dst_col and self.can_move_to_tableau(sub_run, dst_col): return True # 3. Erreichbare Karten aus Waste / Stock prüfen for r_card in self._reachable_stock_waste_cards(): if self._card_can_play_anywhere(r_card): return True # 4. Falls der Stock noch ungezogene / recyclebare Karten hat, die der Spieler noch selbst aufdecken darf, # erst dann als Deadlock melden, wenn entweder gar keine spielbare Karte drin steckt ODER das rote X aktiv ist. # (Schritt 3 hat bereits geprüft, ob im erreichbaren Stock überhaupt noch eine spielbare Karte liegt!) # 5. Seltener Rettungszug: Karte von Foundation aufs Tableau holen, um damit sofort eine Tableau-Spitze aufzunehmen for f_idx, f_pile in enumerate(self.foundations): if not f_pile or f_pile[-1].value <= 2: continue f_card = f_pile[-1] for dst_col in range(self.NUM_TABLEAU): if not self.can_move_to_tableau([f_card], dst_col): continue # Bringt dieser Rückzug einer anderen Tableau-Karte sofort ein neues Ziel? for other_col, o_pile in enumerate(self.tableau): if other_col == dst_col or not o_pile: continue o_first_up = next((i for i, c in enumerate(o_pile) if c.face_up), len(o_pile)) head = o_pile[o_first_up] if head.is_red != f_card.is_red and head.value + 1 == f_card.value: return True return False def get_hint(self) -> dict | None: if self.waste: w_card = self.waste[-1] f_idx = self.foundation_index_for_suit(w_card.suit) if self.can_move_to_foundation(w_card, f_idx): return {"type": "waste_to_foundation", "dst": f_idx} for col_idx, col in enumerate(self.tableau): if col: t_card = col[-1] f_idx = self.foundation_index_for_suit(t_card.suit) if self.can_move_to_foundation(t_card, f_idx): return {"type": "tableau_to_foundation", "src_col": col_idx, "dst": f_idx} for src_col, col in enumerate(self.tableau): if not col: continue first_up_idx = next((i for i, c in enumerate(col) if c.face_up), len(col)) if first_up_idx >= len(col): continue moving = col[first_up_idx:] if first_up_idx == 0 and moving[0].value == 13: continue for dst_col in range(self.NUM_TABLEAU): if src_col != dst_col and self.can_move_to_tableau(moving, dst_col): return { "type": "tableau_to_tableau", "src_col": src_col, "card_idx": first_up_idx, "dst_col": dst_col, } if self.waste: w_card = self.waste[-1] for dst_col in range(self.NUM_TABLEAU): if self.can_move_to_tableau([w_card], dst_col): return {"type": "waste_to_tableau", "dst_col": dst_col} if self.can_draw_or_recycle(): return {"type": "draw_stock"} return None # --- Persistenz --- 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"] ]