# -*- coding: utf-8 -*- # games/solitaire/klondike/models/klondike_solver.py from __future__ import annotations import heapq import random from dataclasses import dataclass from games.solitaire.base.solitaire_core import SOLITAIRE_RANKS, SolitaireCard from resources.code_res.game_constants import SUITS # Kompakte Karten-Codierung 0..51: card_id = suit_idx * 13 + (value - 1) # SUITS = ('C', 'D', 'H', 'S') -> Rot sind Indizes 1 ('D') und 2 ('H') _IS_RED = tuple((c // 13) in (1, 2) for c in range(52)) _SUIT = tuple(c // 13 for c in range(52)) _VAL = tuple((c % 13) + 1 for c in range(52)) @dataclass class SolveReport: solvable: bool nodes_expanded: int backtracks: int layout_hardness: float def _encode_card(card: SolitaireCard) -> int: return SUITS.index(card.suit) * 13 + (card.value - 1) def _decode_card(cid: int, face_up: bool = False) -> SolitaireCard: return SolitaireCard( suit=SUITS[_SUIT[cid]], rank=SOLITAIRE_RANKS[cid % 13], face_up=face_up, deck_id=0, ) def evaluate_initial_hardness(deck_ids: list[int], draw_count: int) -> float: """ Bewertet die strukturelle Schwierigkeit eines 52er-Decks vor dem Lösen: - Tief vergrabene Asse & Zweien im Tableau erhöhen den Wert stark. - Hohe verdeckte Karten über niedrigen Karten und wenige Startzüge erhöhen den Wert. """ score = 0.0 cursor = 0 upcards: list[int] = [] for col_idx in range(7): col = deck_ids[cursor : cursor + col_idx + 1] cursor += col_idx + 1 hidden = col[:-1] top = col[-1] upcards.append(top) # Sofort sichtbare Asse/Zweien machen den Start leichter if _VAL[top] == 1: score -= 10.0 elif _VAL[top] == 2: score -= 5.0 elif _VAL[top] == 13 and col_idx > 0: score += 2.5 depth_from_top = len(hidden) for pos, h_cid in enumerate(hidden): buried_weight = depth_from_top - pos v = _VAL[h_cid] if v == 1: score += 7.5 + buried_weight * 2.4 elif v == 2: score += 4.5 + buried_weight * 1.6 elif v <= 4: score += 1.8 + buried_weight * 0.7 # Prüfe, wie viele direkte Tableau-Züge am Start existieren initial_pairs = 0 for i, c_a in enumerate(upcards): for j, c_b in enumerate(upcards): if i != j and _IS_RED[c_a] != _IS_RED[c_b] and _VAL[c_a] + 1 == _VAL[c_b]: initial_pairs += 1 score -= initial_pairs * 4.5 if draw_count == 3: score += 8.0 return score def _safe_auto_promote( found: list[int], tab_down: list[list[int]], tab_up: list[list[int]], waste: list[int], ) -> None: """ Schiebt Karten automatisch auf die Foundation, solange dadurch garantiert keine Ablagemöglichkeit für niedrigere Karten der Gegenfarbe verloren geht. """ changed = True while changed: changed = False min_black = min(found[0], found[3]) min_red = min(found[1], found[2]) # 1. Oberste Waste-Karte prüfen if waste: cid = waste[-1] s, v = _SUIT[cid], _VAL[cid] if v == found[s] + 1: opp_min = min_black if _IS_RED[cid] else min_red if v <= 2 or v <= opp_min + 1: waste.pop() found[s] += 1 changed = True continue # 2. Tableau-Spitzen prüfen for col in range(7): if not tab_up[col]: continue cid = tab_up[col][-1] s, v = _SUIT[cid], _VAL[cid] if v == found[s] + 1: opp_min = min_black if _IS_RED[cid] else min_red if v <= 2 or v <= opp_min + 1: tab_up[col].pop() found[s] += 1 if not tab_up[col] and tab_down[col]: tab_up[col].append(tab_down[col].pop()) changed = True break def _make_state_key( found: tuple[int, ...], tab_down: tuple[tuple[int, ...], ...], tab_up: tuple[tuple[int, ...], ...], stock: tuple[int, ...], waste: tuple[int, ...], redeals: int, ) -> tuple: # Leere Spalten sind untereinander symmetrisch -> kanonische Sortierung spart massiv Suchraum cols = sorted(zip(tab_down, tab_up)) return (found, tuple(cols), stock, waste, redeals) def solve_klondike_deck( deck_ids: list[int], draw_count: int = 1, redeal_limit: int | None = None, max_nodes: int = 4500, ) -> SolveReport: """ Best-First-Solver für Klondike (Draw 1 & Draw 3). Gibt zurück, ob eine Gewinnsequenz bis zu allen 52 Karten auf der Foundation existiert. """ hardness = evaluate_initial_hardness(deck_ids, draw_count) tab_down_init: list[list[int]] = [] tab_up_init: list[list[int]] = [] cursor = 0 for col_idx in range(7): col = deck_ids[cursor : cursor + col_idx + 1] cursor += col_idx + 1 tab_down_init.append(col[:-1]) tab_up_init.append([col[-1]]) stock_init = list(deck_ids[cursor:]) waste_init: list[int] = [] found_init = [0, 0, 0, 0] _safe_auto_promote(found_init, tab_down_init, tab_up_init, waste_init) if sum(found_init) == 52: return SolveReport(True, 1, 0, hardness) start_state = ( tuple(found_init), tuple(tuple(c) for c in tab_down_init), tuple(tuple(c) for c in tab_up_init), tuple(stock_init), tuple(waste_init), 0, ) visited: set[tuple] = {_make_state_key(*start_state)} pq: list[tuple[int, int, int, tuple]] = [] counter = 0 def heuristic(st: tuple) -> int: fnd, t_down, _t_up, _stk, _wst, rdl = st hidden_cnt = sum(len(c) for c in t_down) fnd_sum = sum(fnd) return (52 - fnd_sum) * 4 + hidden_cnt * 9 + rdl * 3 heapq.heappush(pq, (heuristic(start_state), 0, counter, start_state)) nodes = 0 backtracks = 0 best_progress = sum(found_init) while pq and nodes < max_nodes: _prio, depth, _tie, state = heapq.heappop(pq) fnd, t_down, t_up, stk, wst, redeals = state nodes += 1 f_sum = sum(fnd) if f_sum == 52: return SolveReport(True, nodes, backtracks, hardness) if f_sum > best_progress: best_progress = f_sum elif f_sum < best_progress - 2: backtracks += 1 # Wenn alle verdeckten Karten offen sind und Draw 1 aktiv ist (oder Stock+Waste leer), # ist die Partie in Klondike deterministisch gewonnen. hidden_total = sum(len(c) for c in t_down) if hidden_total == 0 and (draw_count == 1 or (not stk and not wst)): return SolveReport(True, nodes, backtracks, hardness) next_states: list[tuple] = [] def push_candidate(nf, nd, nu, ns, nw, nr): _safe_auto_promote(nf, nd, nu, nw) cand = ( tuple(nf), tuple(tuple(c) for c in nd), tuple(tuple(c) for c in nu), tuple(ns), tuple(nw), nr, ) key = _make_state_key(*cand) if key not in visited: visited.add(key) next_states.append(cand) # 1. Explizite Foundation-Züge (für Karten über dem Safe-Auto-Threshold) if wst: w_cid = wst[-1] ws = _SUIT[w_cid] if _VAL[w_cid] == fnd[ws] + 1: nf, nd, nu, nw = list(fnd), [list(c) for c in t_down], [list(c) for c in t_up], list(wst[:-1]) nf[ws] += 1 push_candidate(nf, nd, nu, list(stk), nw, redeals) for src in range(7): if t_up[src]: t_cid = t_up[src][-1] ts = _SUIT[t_cid] if _VAL[t_cid] == fnd[ts] + 1: nf = list(fnd) nd = [list(c) for c in t_down] nu = [list(c) for c in t_up] nu[src].pop() nf[ts] += 1 if not nu[src] and nd[src]: nu[src].append(nd[src].pop()) push_candidate(nf, nd, nu, list(stk), list(wst), redeals) # 2. Tableau -> Tableau Züge (fokus auf Züge, die verdeckte Karten freilegen oder Sequenzen vereinen) empty_col_used = False for src in range(7): up_col = t_up[src] if not up_col: continue # Entweder den gesamten offenen Run bewegen (legt Karte frei / leert Spalte) # oder Teil-Run nur dann, wenn die darunterliegende Karte dadurch auf eine Foundation passt. candidate_indices = [0] for split_idx in range(1, len(up_col)): exposed = up_col[split_idx - 1] if _VAL[exposed] == fnd[_SUIT[exposed]] + 1: candidate_indices.append(split_idx) for idx in candidate_indices: head = up_col[idx] h_val, h_red = _VAL[head], _IS_RED[head] # Sinnloses Verschieben eines Königs von einer bereits nackten Spalte in eine andere leere Spalte verhindern if idx == 0 and not t_down[src] and h_val == 13: continue for dst in range(7): if src == dst: continue if not t_up[dst]: if h_val != 13 or empty_col_used: continue empty_col_used = True else: dst_top = t_up[dst][-1] if _IS_RED[dst_top] == h_red or _VAL[dst_top] != h_val + 1: continue nf = list(fnd) nd = [list(c) for c in t_down] nu = [list(c) for c in t_up] moving = nu[src][idx:] del nu[src][idx:] nu[dst].extend(moving) if not nu[src] and nd[src]: nu[src].append(nd[src].pop()) push_candidate(nf, nd, nu, list(stk), list(wst), redeals) # 3. Waste -> Tableau if wst: w_cid = wst[-1] w_val, w_red = _VAL[w_cid], _IS_RED[w_cid] empty_w_used = False for dst in range(7): if not t_up[dst]: if w_val != 13 or empty_w_used: continue empty_w_used = True else: dst_top = t_up[dst][-1] if _IS_RED[dst_top] == w_red or _VAL[dst_top] != w_val + 1: continue nf = list(fnd) nd = [list(c) for c in t_down] nu = [list(c) for c in t_up] nw = list(wst[:-1]) nu[dst].append(w_cid) push_candidate(nf, nd, nu, list(stk), nw, redeals) # 4. Stock ziehen oder recyclen (alle direkt erreichbaren Zieh-Positionen generieren) if stk or wst: sim_stk = list(stk) sim_wst = list(wst) sim_rdl = redeals # Einmal ziehen if sim_stk: cnt = min(draw_count, len(sim_stk)) for _ in range(cnt): sim_wst.append(sim_stk.pop()) push_candidate( list(fnd), [list(c) for c in t_down], [list(c) for c in t_up], sim_stk, sim_wst, sim_rdl, ) elif sim_wst: if redeal_limit is None or sim_rdl < redeal_limit: recycled = list(reversed(sim_wst)) sim_wst = [] cnt = min(draw_count, len(recycled)) for _ in range(cnt): sim_wst.append(recycled.pop()) push_candidate( list(fnd), [list(c) for c in t_down], [list(c) for c in t_up], recycled, sim_wst, sim_rdl + 1, ) for ns in next_states: if sum(ns[0]) == 52: return SolveReport(True, nodes, backtracks, hardness) counter += 1 heapq.heappush(pq, (heuristic(ns), depth + 1, counter, ns)) return SolveReport(False, nodes, backtracks, hardness) def generate_solvable_klondike_deck( draw_count: int = 1, difficulty: int = 1, redeal_limit: int | None = None, seed: int | None = None, ) -> list[SolitaireCard]: """ Erzeugt ein garantiert lösbares 52-Karten-Deck passend zur gewählten Schwierigkeitsstufe (0..3). Wählt aus lösbaren Deals denjenigen aus, dessen Komplexität am besten zur Stufe passt. """ rng = random.Random(seed) if seed is not None else random.Random() diff = max(0, min(3, int(difficulty))) # Ziel-Komplexitätswert (Kombination aus Layout-Härte + Solver-Aufwand) target_scores = { 0: 15.0, # Leicht: offen, niedrige Karten früh frei 1: 52.0, # Normal: klassisch ausgewogen 2: 92.0, # Schwer: tiefe Blockaden & Backtracking 3: 145.0, # Gottheit: vergrabene Asse & enge Lösungswege } target = target_scores[diff] # Schnelles Vorfiltern vor dem teureren Solver-Lauf hardness_bounds = { 0: (-60.0, 32.0), 1: (22.0, 68.0), 2: (52.0, 110.0), 3: (72.0, 999.0), } h_min, h_max = hardness_bounds[diff] # Wie viele lösbare Kandidaten wir sammeln, um einen richtig guten Treffer zu landen desired_pool = 2 if diff in (0, 1) else 3 max_attempts = 260 node_budget = 2600 if diff <= 1 else 4800 solvable_candidates: list[tuple[float, list[int]]] = [] base_deck = list(range(52)) for attempt in range(max_attempts): trial = list(base_deck) rng.shuffle(trial) # In den ersten 70% der Versuche nur Layouts lösen, die zur gewünschten Stufe passen h_val = evaluate_initial_hardness(trial, draw_count) if attempt < int(max_attempts * 0.70) and not (h_min <= h_val <= h_max): continue report = solve_klondike_deck( trial, draw_count=draw_count, redeal_limit=redeal_limit, max_nodes=node_budget, ) if not report.solvable: continue composite = report.layout_hardness + (report.nodes_expanded / 38.0) + (report.backtracks * 1.4) solvable_candidates.append((composite, trial)) # Früher Ausstieg, wenn ein Kandidat bereits sehr nah am Zielbereich liegt if diff == 0 and composite <= 26.0: break if diff == 1 and 34.0 <= composite <= 72.0: break if diff == 2 and composite >= 82.0: break if diff == 3 and composite >= 115.0: break if len(solvable_candidates) >= desired_pool: break # Sicherheitsnetz: Falls ein extremes Gottheit-Filterfenster im seltenen Fall keinen Treffer hatte, # suche ohne Vorfilter weiter, bis garantiert ein lösbares Deck steht! while not solvable_candidates: trial = list(base_deck) rng.shuffle(trial) report = solve_klondike_deck( trial, draw_count=draw_count, redeal_limit=redeal_limit, max_nodes=5500, ) if report.solvable: composite = report.layout_hardness + (report.nodes_expanded / 38.0) solvable_candidates.append((composite, trial)) if diff == 3: best_deck_ids = max(solvable_candidates, key=lambda item: item[0])[1] elif diff == 0: best_deck_ids = min(solvable_candidates, key=lambda item: item[0])[1] else: best_deck_ids = min(solvable_candidates, key=lambda item: abs(item[0] - target))[1] return [_decode_card(cid, face_up=False) for cid in best_deck_ids]