# -*- coding: utf-8 -*- # games/solitaire/freecell/models/freecell_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 _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 FreeCellSolveReport: solvable: bool nodes_expanded: int backtracks: int layout_hardness: float def _decode_card(cid: int) -> SolitaireCard: return SolitaireCard( suit=SUITS[_SUIT[cid]], rank=SOLITAIRE_RANKS[cid % 13], face_up=True, deck_id=0, ) def _deal_columns_from_deck(deck_ids: list[int]) -> list[list[int]]: cols: list[list[int]] = [[] for _ in range(8)] for idx, cid in enumerate(deck_ids): cols[idx % 8].append(cid) return cols def evaluate_freecell_hardness(cols: list[list[int]]) -> float: """ Bewertet die strukturelle Schwierigkeit einer FreeCell-Startauslage: - Tief vergrabene Asse/Zweien (ganz oben in den 7er-/6er-Spalten) erhöhen den Wert stark. - Hohe Karten, die unterhalb niedrigerer Karten liegen (Inversionen), erhöhen den Wert. - Bereits natürlich geordnete Paare senken den Wert. """ score = 0.0 for col in cols: n = len(col) for pos, cid in enumerate(col): depth_from_bottom = n - 1 - pos v = _VAL[cid] if v == 1: score += depth_from_bottom * 4.2 elif v == 2: score += depth_from_bottom * 2.6 elif v == 3: score += depth_from_bottom * 1.2 if pos < n - 1: below = col[pos + 1] if _IS_RED[cid] != _IS_RED[below] and _VAL[cid] == _VAL[below] + 1: score -= 3.5 elif _VAL[cid] < _VAL[below]: score += 1.4 # Direkte Startzüge zwischen den 8 unteren Spitzen zählen bottoms = [c[-1] for c in cols if c] natural_moves = 0 for i, ca in enumerate(bottoms): if _VAL[ca] == 1: score -= 6.0 for j, cb in enumerate(bottoms): if i != j and _IS_RED[ca] != _IS_RED[cb] and _VAL[ca] + 1 == _VAL[cb]: natural_moves += 1 score -= natural_moves * 2.8 return score def _safe_auto_promote( found: list[int], freecells: list[int], cols: list[list[int]], ) -> None: """Legt Karten sicher auf die Foundation, sobald keine Gegenfarben-Karte sie mehr zum Bauen braucht.""" changed = True while changed: changed = False min_black = min(found[0], found[3]) min_red = min(found[1], found[2]) for idx, cid in enumerate(freecells): if cid < 0: continue 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: freecells[idx] = -1 found[s] += 1 changed = True break if changed: continue for col in cols: if not col: continue cid = 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: col.pop() found[s] += 1 changed = True break def _state_key( found: tuple[int, ...], freecells: tuple[int, ...], cols: tuple[tuple[int, ...], ...], ) -> tuple: # Freie Zellen und Spalten sind untereinander symmetrisch -> Sortieren kollabiert Duplikate enorm return (found, tuple(sorted(freecells)), tuple(sorted(cols))) def _ordered_tail_len(col: tuple[int, ...]) -> int: if not col: return 0 length = 1 for i in range(len(col) - 1, 0, -1): lower = col[i] upper = col[i - 1] if _IS_RED[upper] != _IS_RED[lower] and _VAL[upper] == _VAL[lower] + 1: length += 1 else: break return length def solve_freecell_deal(deck_ids: list[int], max_nodes: int = 4200) -> FreeCellSolveReport: cols_init = _deal_columns_from_deck(deck_ids) hardness = evaluate_freecell_hardness(cols_init) found_init = [0, 0, 0, 0] fc_init = [-1, -1, -1, -1] _safe_auto_promote(found_init, fc_init, cols_init) if sum(found_init) == 52: return FreeCellSolveReport(True, 1, 0, hardness) start_state = ( tuple(found_init), tuple(fc_init), tuple(tuple(c) for c in cols_init), ) visited: set[tuple] = {_state_key(*start_state)} pq: list[tuple[int, int, int, tuple]] = [] counter = 0 def heuristic(st: tuple) -> int: fnd, fcs, cls = st remaining = 52 - sum(fnd) occupied_fc = sum(1 for x in fcs if x >= 0) empty_cols = sum(1 for c in cls if not c) disorder = 0 for c in cls: for k in range(len(c) - 1): if not (_IS_RED[c[k]] != _IS_RED[c[k + 1]] and _VAL[c[k]] == _VAL[c[k + 1]] + 1): disorder += 1 return remaining * 5 + disorder * 4 + occupied_fc * 3 - empty_cols * 4 heapq.heappush(pq, (heuristic(start_state), 0, counter, start_state)) nodes = 0 backtracks = 0 best_found = sum(found_init) while pq and nodes < max_nodes: _prio, depth, _tie, state = heapq.heappop(pq) fnd, fcs, cls = state nodes += 1 f_sum = sum(fnd) if f_sum == 52: return FreeCellSolveReport(True, nodes, backtracks, hardness) if f_sum > best_found: best_found = f_sum elif f_sum < best_found - 2: backtracks += 1 # Sind alle Spalten bereits streng absteigend sortiert, ist das Spiel gewonnen if all(_ordered_tail_len(c) == len(c) for c in cls): only_descending = True for c in cls: for k in range(len(c) - 1): if _VAL[c[k]] < _VAL[c[k + 1]]: only_descending = False break if only_descending and f_sum >= 36: return FreeCellSolveReport(True, nodes, backtracks, hardness) free_fc_count = sum(1 for x in fcs if x < 0) empty_col_indices = [i for i, c in enumerate(cls) if not c] empty_col_count = len(empty_col_indices) next_states: list[tuple] = [] def push_cand(nf: list[int], nfc: list[int], ncls: list[list[int]]): _safe_auto_promote(nf, nfc, ncls) cand = (tuple(nf), tuple(nfc), tuple(tuple(c) for c in ncls)) k = _state_key(*cand) if k not in visited: visited.add(k) next_states.append(cand) # 1. Explizite Foundation-Züge (FreeCell & Spaltenspitzen) for fc_i, cid in enumerate(fcs): if cid >= 0 and _VAL[cid] == fnd[_SUIT[cid]] + 1: nf, nfc, ncls = list(fnd), list(fcs), [list(c) for c in cls] nfc[fc_i] = -1 nf[_SUIT[cid]] += 1 push_cand(nf, nfc, ncls) for col_i, col in enumerate(cls): if col: cid = col[-1] if _VAL[cid] == fnd[_SUIT[cid]] + 1: nf, nfc, ncls = list(fnd), list(fcs), [list(c) for c in cls] ncls[col_i].pop() nf[_SUIT[cid]] += 1 push_cand(nf, nfc, ncls) # 2. FreeCell -> Tableau (belegte Spalten + max. eine leere Spalte) seen_fc_cards: set[int] = set() for fc_i, cid in enumerate(fcs): if cid < 0 or cid in seen_fc_cards: continue seen_fc_cards.add(cid) used_empty = False for dst_i, dst_col in enumerate(cls): if not dst_col: if used_empty: continue used_empty = True else: top = dst_col[-1] if _IS_RED[top] == _IS_RED[cid] or _VAL[top] != _VAL[cid] + 1: continue nf, nfc, ncls = list(fnd), list(fcs), [list(c) for c in cls] nfc[fc_i] = -1 ncls[dst_i].append(cid) push_cand(nf, nfc, ncls) # 3. Tableau -> Tableau (inkl. Supermoves über freie Zellen & leere Hilfsspalten) for src_i, src_col in enumerate(cls): if not src_col: continue tail_max = _ordered_tail_len(src_col) used_empty_for_src = False for dst_i, dst_col in enumerate(cls): if src_i == dst_i: continue if not dst_col: if used_empty_for_src: continue aux_empty = max(0, empty_col_count - 1) max_cap = (free_fc_count + 1) * (1 << aux_empty) # Ganzen Run in leere Spalte schieben bringt nichts, wenn nichts darunter freigelegt wird max_useful = min(tail_max, max_cap, len(src_col) - 1) if max_useful <= 0: continue used_empty_for_src = True # Bevorzuge das Freilegen des kompletten geordneten Runs nf, nfc, ncls = list(fnd), list(fcs), [list(c) for c in cls] moving = ncls[src_i][-max_useful:] del ncls[src_i][-max_useful:] ncls[dst_i].extend(moving) push_cand(nf, nfc, ncls) else: dst_top = dst_col[-1] max_cap = (free_fc_count + 1) * (1 << empty_col_count) limit = min(tail_max, max_cap) # Genau eine Länge k im geordneten Tail kann wertmäßig auf dst_top passen! needed_val = _VAL[dst_top] - 1 head_idx = len(src_col) - limit for idx in range(head_idx, len(src_col)): cand_head = src_col[idx] if _VAL[cand_head] == needed_val and _IS_RED[cand_head] != _IS_RED[dst_top]: nf, nfc, ncls = list(fnd), list(fcs), [list(c) for c in cls] moving = ncls[src_i][idx:] del ncls[src_i][idx:] ncls[dst_i].extend(moving) push_cand(nf, nfc, ncls) break # 4. Tableau-Spitze -> erste freie FreeCell if free_fc_count > 0: first_empty_fc = fcs.index(-1) for src_i, src_col in enumerate(cls): if not src_col: continue nf, nfc, ncls = list(fnd), list(fcs), [list(c) for c in cls] nfc[first_empty_fc] = ncls[src_i].pop() push_cand(nf, nfc, ncls) for ns in next_states: if sum(ns[0]) == 52: return FreeCellSolveReport(True, nodes, backtracks, hardness) counter += 1 heapq.heappush(pq, (heuristic(ns), depth + 1, counter, ns)) return FreeCellSolveReport(False, nodes, backtracks, hardness) def generate_solvable_freecell_columns( difficulty: int = 1, seed: int | None = None, ) -> list[list[SolitaireCard]]: """ Erzeugt 8 garantiert lösbare FreeCell-Spalten passend zur gewählten Schwierigkeitsstufe (0..3). """ rng = random.Random(seed) if seed is not None else random.Random() diff = max(0, min(3, int(difficulty))) target_scores = { 0: 28.0, # Leicht: niedrige Karten früh frei, kaum Blockaden 1: 68.0, # Normal: klassisches FreeCell-Gefühl 2: 108.0, # Schwer: vergrabene Asse, engere Zell-Kapazität 3: 155.0, # Gottheit: maximale Verzahnung & Backtracking } target = target_scores[diff] hardness_bounds = { 0: (-80.0, 48.0), 1: (38.0, 86.0), 2: (72.0, 130.0), 3: (92.0, 999.0), } h_min, h_max = hardness_bounds[diff] max_attempts = 200 node_budget = 2600 if diff <= 1 else 4500 desired_pool = 2 if diff <= 1 else 3 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) cols_preview = _deal_columns_from_deck(trial) h_val = evaluate_freecell_hardness(cols_preview) if attempt < int(max_attempts * 0.70) and not (h_min <= h_val <= h_max): continue report = solve_freecell_deal(trial, max_nodes=node_budget) if not report.solvable: continue composite = report.layout_hardness + (report.nodes_expanded / 32.0) + (report.backtracks * 1.5) solvable_candidates.append((composite, trial)) if diff == 0 and composite <= 36.0: break if diff == 1 and 50.0 <= composite <= 84.0: break if diff == 2 and composite >= 96.0: break if diff == 3 and composite >= 128.0: break if len(solvable_candidates) >= desired_pool: break while not solvable_candidates: trial = list(base_deck) rng.shuffle(trial) report = solve_freecell_deal(trial, max_nodes=5000) if report.solvable: composite = report.layout_hardness + (report.nodes_expanded / 32.0) solvable_candidates.append((composite, trial)) if diff == 3: best_deck = max(solvable_candidates, key=lambda x: x[0])[1] elif diff == 0: best_deck = min(solvable_candidates, key=lambda x: x[0])[1] else: best_deck = min(solvable_candidates, key=lambda x: abs(x[0] - target))[1] raw_cols = _deal_columns_from_deck(best_deck) return [[_decode_card(cid) for cid in col] for col in raw_cols]