# -*- coding: utf-8 -*- # games/solitaire/pyramid/models/pyramid_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 PYRAMID_REDEALS_BY_DIFF, SUITS _SUIT = tuple(c // 13 for c in range(52)) _VAL = tuple((c % 13) + 1 for c in range(52)) _CHILD_MASKS: tuple[int, ...] = tuple( 0 if r == 6 else ( (1 << (((r + 1) * (r + 2)) // 2 + c)) | (1 << (((r + 1) * (r + 2)) // 2 + c + 1)) ) for r in range(7) for c in range(r + 1) ) @dataclass class PyramidSolveReport: solvable: bool nodes_expanded: 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 _exposed_pyramid_indices(pyr_mask: int) -> list[int]: out: list[int] = [] m = pyr_mask while m: lsb = m & -m idx = lsb.bit_length() - 1 if (pyr_mask & _CHILD_MASKS[idx]) == 0: out.append(idx) m ^= lsb return out def evaluate_pyramid_hardness(pyr_ids: list[int], stock_ids: list[int]) -> float: score = 0.0 for r in range(7): row_base = (r * (r + 1)) // 2 depth_weight = (6 - r) * 1.6 for c in range(r + 1): idx = row_base + c v = _VAL[pyr_ids[idx]] if v == 13: score -= 2.8 if r == 6 else 1.2 if r < 6: left_v = _VAL[pyr_ids[((r + 1) * (r + 2)) // 2 + c]] right_v = _VAL[pyr_ids[((r + 1) * (r + 2)) // 2 + c + 1]] if v + left_v == 13: score += 6.5 + depth_weight if v + right_v == 13: score += 6.5 + depth_weight bottom_vals = [_VAL[pyr_ids[21 + c]] for c in range(7)] if stock_ids: bottom_vals.append(_VAL[stock_ids[-1]]) immediate_pairs = sum(1 for v in bottom_vals if v == 13) for i in range(len(bottom_vals)): for j in range(i + 1, len(bottom_vals)): if bottom_vals[i] + bottom_vals[j] == 13: immediate_pairs += 1 score -= immediate_pairs * 4.0 return score def solve_pyramid_deal( deck_ids: list[int], max_redeals: int, max_nodes: int = 3800 ) -> PyramidSolveReport: """ Prüft Lösbarkeit mit offenem Talon (stock_t[-1]) + offener Ablage (waste_t[-1]): Beide Oberkarten sind mit freien Pyramidenkarten UND direkt miteinander kombinierbar. """ pyr_ids = deck_ids[:28] stock_ids = deck_ids[28:] hardness = evaluate_pyramid_hardness(pyr_ids, stock_ids) init_mask = (1 << 28) - 1 start_state = (init_mask, tuple(stock_ids), (), max_redeals) visited: set[tuple] = {start_state} pq: list[tuple[int, int, int, tuple]] = [] counter = 0 def heuristic(pyr_m: int, redeals_rem: int) -> int: return pyr_m.bit_count() * 4 - redeals_rem * 2 heapq.heappush(pq, (heuristic(init_mask, max_redeals), 0, counter, start_state)) nodes = 0 while pq and nodes < max_nodes: _prio, depth, _tie, state = heapq.heappop(pq) pyr_m, stock_t, waste_t, redeals_rem = state nodes += 1 if pyr_m == 0: return PyramidSolveReport(True, nodes, hardness) exposed = _exposed_pyramid_indices(pyr_m) next_states: list[tuple] = [] # 1. Freie Könige (13) direkt abräumen (Pyramide, linker Stapel oder rechte Ablage) king_cleared = False for idx in exposed: if _VAL[pyr_ids[idx]] == 13: next_states.append((pyr_m & ~(1 << idx), stock_t, waste_t, redeals_rem)) king_cleared = True break if not king_cleared and stock_t and _VAL[stock_t[-1]] == 13: next_states.append((pyr_m, stock_t[:-1], waste_t, redeals_rem)) king_cleared = True if not king_cleared and waste_t and _VAL[waste_t[-1]] == 13: next_states.append((pyr_m, stock_t, waste_t[:-1], redeals_rem)) king_cleared = True if not king_cleared: # 2. Zwei freie Pyramidenkarten paaren for i_pos in range(len(exposed)): idx_a = exposed[i_pos] va = _VAL[pyr_ids[idx_a]] for j_pos in range(i_pos + 1, len(exposed)): idx_b = exposed[j_pos] if va + _VAL[pyr_ids[idx_b]] == 13: nm = pyr_m & ~((1 << idx_a) | (1 << idx_b)) next_states.append((nm, stock_t, waste_t, redeals_rem)) # 3. Pyramidenkarte + linker Stapel / rechte Ablage if stock_t: vs = _VAL[stock_t[-1]] for idx_a in exposed: if _VAL[pyr_ids[idx_a]] + vs == 13: next_states.append((pyr_m & ~(1 << idx_a), stock_t[:-1], waste_t, redeals_rem)) if waste_t: vw = _VAL[waste_t[-1]] for idx_a in exposed: if _VAL[pyr_ids[idx_a]] + vw == 13: next_states.append((pyr_m & ~(1 << idx_a), stock_t, waste_t[:-1], redeals_rem)) # 4. Linker Stapel + rechte Ablage direkt miteinander paaren if stock_t and waste_t and (_VAL[stock_t[-1]] + _VAL[waste_t[-1]] == 13): next_states.append((pyr_m, stock_t[:-1], waste_t[:-1], redeals_rem)) # 5. Button "Nächste Karte": Linke Karte nach rechts legen oder Redeal if stock_t: next_states.append((pyr_m, stock_t[:-1], waste_t + (stock_t[-1],), redeals_rem)) elif waste_t and redeals_rem > 0: recycled_stock = tuple(reversed(waste_t)) next_states.append((pyr_m, recycled_stock, (), redeals_rem - 1)) for ns in next_states: if ns[0] == 0: return PyramidSolveReport(True, nodes, hardness) if ns not in visited: visited.add(ns) counter += 1 heapq.heappush( pq, (heuristic(ns[0], ns[3]) + depth // 3, depth + 1, counter, ns) ) return PyramidSolveReport(False, nodes, hardness) def generate_solvable_pyramid_deal( difficulty: int = 1, seed: int | None = None, ) -> tuple[list[list[SolitaireCard | None]], list[SolitaireCard]]: rng = random.Random(seed) if seed is not None else random.Random() diff = max(0, min(3, int(difficulty))) max_redeals = PYRAMID_REDEALS_BY_DIFF.get(diff, 2) hardness_targets = {0: -6.0, 1: 8.0, 2: 18.0, 3: 28.0} target = hardness_targets[diff] node_budget = 2800 if diff <= 1 else 4400 base_deck = list(range(52)) candidates: list[tuple[float, list[int]]] = [] for _attempt in range(280): trial = list(base_deck) rng.shuffle(trial) report = solve_pyramid_deal(trial, max_redeals=max_redeals, max_nodes=node_budget) if not report.solvable: continue composite = report.layout_hardness + (report.nodes_expanded / 45.0) candidates.append((composite, trial)) if diff == 0 and composite <= 2.0: break if diff == 1 and 2.0 <= composite <= 22.0: break if diff == 2 and composite >= 14.0 and len(candidates) >= 2: break if diff == 3 and len(candidates) >= 2: break if len(candidates) >= 3: break while not candidates: trial = list(base_deck) rng.shuffle(trial) report = solve_pyramid_deal(trial, max_redeals=max_redeals, max_nodes=5200) if report.solvable: candidates.append((report.layout_hardness + report.nodes_expanded / 45.0, trial)) if diff == 3: best_ids = max(candidates, key=lambda x: x[0])[1] elif diff == 0: best_ids = min(candidates, key=lambda x: x[0])[1] else: best_ids = min(candidates, key=lambda x: abs(x[0] - target))[1] pyramid: list[list[SolitaireCard | None]] = [] cursor = 0 for r in range(7): row = [_decode_card(best_ids[cursor + c]) for c in range(r + 1)] pyramid.append(row) cursor += r + 1 stock = [_decode_card(cid) for cid in best_ids[28:]] return pyramid, stock