264 lines
9.3 KiB
Python
264 lines
9.3 KiB
Python
|
|
# -*- coding: utf-8 -*-
|
||
|
|
# games/solitaire/tripeaks/models/tripeaks_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, TRIPEAKS_REDEALS_BY_DIFF
|
||
|
|
|
||
|
|
_SUIT = tuple(c // 13 for c in range(52))
|
||
|
|
_VAL = tuple((c % 13) + 1 for c in range(52))
|
||
|
|
|
||
|
|
# Klassische 28-Karten-TriPeaks-Geometrie in Halb-Karten-Schritten (x_half = 0..18):
|
||
|
|
# Reihe 0 (3 Gipfel): Indices 0..2 -> x_half: 3, 9, 15
|
||
|
|
# Reihe 1 (6 Karten): Indices 3..8 -> x_half: 2,4 | 8,10 | 14,16
|
||
|
|
# Reihe 2 (9 Karten): Indices 9..17 -> x_half: 1,3,5 | 7,9,11 | 13,15,17
|
||
|
|
# Reihe 3 (10 Basis): Indices 18..27 -> x_half: 0,2,4,6,8,10,12,14,16,18
|
||
|
|
TRIPEAKS_LAYOUT: tuple[tuple[int, int], ...] = (
|
||
|
|
# Row 0 (Peaks)
|
||
|
|
(0, 3), (0, 9), (0, 15),
|
||
|
|
# Row 1
|
||
|
|
(1, 2), (1, 4), (1, 8), (1, 10), (1, 14), (1, 16),
|
||
|
|
# Row 2
|
||
|
|
(2, 1), (2, 3), (2, 5), (2, 7), (2, 9), (2, 11), (2, 13), (2, 15), (2, 17),
|
||
|
|
# Row 3 (Base, initially face-up)
|
||
|
|
(3, 0), (3, 2), (3, 4), (3, 6), (3, 8), (3, 10), (3, 12), (3, 14), (3, 16), (3, 18),
|
||
|
|
)
|
||
|
|
|
||
|
|
_POS_TO_IDX: dict[tuple[int, int], int] = {
|
||
|
|
pos: idx for idx, pos in enumerate(TRIPEAKS_LAYOUT)
|
||
|
|
}
|
||
|
|
|
||
|
|
TRIPEAKS_CHILDREN: tuple[tuple[int, ...], ...] = tuple(
|
||
|
|
()
|
||
|
|
if r == 3
|
||
|
|
else (_POS_TO_IDX[(r + 1, xh - 1)], _POS_TO_IDX[(r + 1, xh + 1)])
|
||
|
|
for (r, xh) in TRIPEAKS_LAYOUT
|
||
|
|
)
|
||
|
|
|
||
|
|
TRIPEAKS_CHILD_MASKS: tuple[int, ...] = tuple(
|
||
|
|
0 if not ch else ((1 << ch[0]) | (1 << ch[1]))
|
||
|
|
for ch in TRIPEAKS_CHILDREN
|
||
|
|
)
|
||
|
|
|
||
|
|
|
||
|
|
def is_tripeaks_adjacent_val(va: int, vb: int) -> bool:
|
||
|
|
diff = abs(va - vb)
|
||
|
|
return diff == 1 or diff == 12
|
||
|
|
|
||
|
|
|
||
|
|
@dataclass
|
||
|
|
class TriPeaksSolveReport:
|
||
|
|
solvable: bool
|
||
|
|
nodes_expanded: int
|
||
|
|
layout_hardness: float
|
||
|
|
|
||
|
|
|
||
|
|
def _decode_card(cid: int, face_up: bool) -> SolitaireCard:
|
||
|
|
return SolitaireCard(
|
||
|
|
suit=SUITS[_SUIT[cid]],
|
||
|
|
rank=SOLITAIRE_RANKS[cid % 13],
|
||
|
|
face_up=face_up,
|
||
|
|
deck_id=0,
|
||
|
|
)
|
||
|
|
|
||
|
|
|
||
|
|
def _exposed_indices(board_mask: int) -> list[int]:
|
||
|
|
out: list[int] = []
|
||
|
|
m = board_mask
|
||
|
|
while m:
|
||
|
|
lsb = m & -m
|
||
|
|
idx = lsb.bit_length() - 1
|
||
|
|
if (board_mask & TRIPEAKS_CHILD_MASKS[idx]) == 0:
|
||
|
|
out.append(idx)
|
||
|
|
m ^= lsb
|
||
|
|
return out
|
||
|
|
|
||
|
|
|
||
|
|
def evaluate_tripeaks_hardness(board_ids: list[int], start_waste_id: int) -> float:
|
||
|
|
"""
|
||
|
|
Bewertet die strukturelle Schwierigkeit eines TriPeaks-Bretts:
|
||
|
|
- Viele benachbarte Ränge (±1) in der offenen 10er-Basisreihe erlauben sofort lange Ketten (leicht).
|
||
|
|
- Gleiche Ränge direkt übereinander oder isolierte Sprünge bremsen Ketten aus (schwer).
|
||
|
|
"""
|
||
|
|
score = 18.0
|
||
|
|
base_vals = [_VAL[board_ids[i]] for i in range(18, 28)]
|
||
|
|
w_val = _VAL[start_waste_id]
|
||
|
|
|
||
|
|
start_hits = sum(1 for v in base_vals if is_tripeaks_adjacent_val(v, w_val))
|
||
|
|
if start_hits == 0:
|
||
|
|
score += 10.0
|
||
|
|
else:
|
||
|
|
score -= start_hits * 3.5
|
||
|
|
|
||
|
|
adj_pairs = 0
|
||
|
|
for i in range(len(base_vals)):
|
||
|
|
for j in range(i + 1, len(base_vals)):
|
||
|
|
if is_tripeaks_adjacent_val(base_vals[i], base_vals[j]):
|
||
|
|
adj_pairs += 1
|
||
|
|
score -= adj_pairs * 1.4
|
||
|
|
|
||
|
|
for idx in range(18):
|
||
|
|
vp = _VAL[board_ids[idx]]
|
||
|
|
c1, c2 = TRIPEAKS_CHILDREN[idx]
|
||
|
|
if vp == _VAL[board_ids[c1]] or vp == _VAL[board_ids[c2]]:
|
||
|
|
score += 3.2
|
||
|
|
if is_tripeaks_adjacent_val(vp, _VAL[board_ids[c1]]):
|
||
|
|
score -= 1.5
|
||
|
|
if is_tripeaks_adjacent_val(vp, _VAL[board_ids[c2]]):
|
||
|
|
score -= 1.5
|
||
|
|
|
||
|
|
return score
|
||
|
|
|
||
|
|
|
||
|
|
def solve_tripeaks_deal(
|
||
|
|
deck_ids: list[int], max_redeals: int, max_nodes: int = 4200
|
||
|
|
) -> TriPeaksSolveReport:
|
||
|
|
"""
|
||
|
|
deck_ids[0..27] = 28 Tableau-Karten
|
||
|
|
deck_ids[28] = erste offene Startkarte auf der Ablage (Waste)
|
||
|
|
deck_ids[29..51] = 23 verdeckte Talon-Karten (stock_t[-1] wird als Nächstes gezogen)
|
||
|
|
"""
|
||
|
|
board_ids = deck_ids[:28]
|
||
|
|
first_waste = deck_ids[28]
|
||
|
|
stock_ids = deck_ids[29:]
|
||
|
|
hardness = evaluate_tripeaks_hardness(board_ids, first_waste)
|
||
|
|
|
||
|
|
init_mask = (1 << 28) - 1
|
||
|
|
# Für 0 Redeals brauchen wir nur den Wert der obersten Waste-Karte zu speichern -> kollabiert Zustände extrem!
|
||
|
|
use_compact_waste = (max_redeals == 0)
|
||
|
|
if use_compact_waste:
|
||
|
|
start_state = (init_mask, len(stock_ids), _VAL[first_waste])
|
||
|
|
else:
|
||
|
|
start_state = (init_mask, tuple(stock_ids), (first_waste,), max_redeals)
|
||
|
|
|
||
|
|
visited: set[tuple] = {start_state}
|
||
|
|
pq: list[tuple[int, int, int, tuple]] = []
|
||
|
|
counter = 0
|
||
|
|
|
||
|
|
heapq.heappush(pq, (28 * 4 - max_redeals * 3, 0, counter, start_state))
|
||
|
|
nodes = 0
|
||
|
|
|
||
|
|
while pq and nodes < max_nodes:
|
||
|
|
_prio, depth, _tie, state = heapq.heappop(pq)
|
||
|
|
nodes += 1
|
||
|
|
|
||
|
|
if use_compact_waste:
|
||
|
|
b_mask, stock_len, top_val = state
|
||
|
|
if b_mask == 0:
|
||
|
|
return TriPeaksSolveReport(True, nodes, hardness)
|
||
|
|
exposed = _exposed_indices(b_mask)
|
||
|
|
next_states: list[tuple] = []
|
||
|
|
|
||
|
|
for idx in exposed:
|
||
|
|
iv = _VAL[board_ids[idx]]
|
||
|
|
if is_tripeaks_adjacent_val(iv, top_val):
|
||
|
|
next_states.append((b_mask & ~(1 << idx), stock_len, iv))
|
||
|
|
|
||
|
|
if stock_len > 0:
|
||
|
|
drawn_cid = stock_ids[stock_len - 1]
|
||
|
|
next_states.append((b_mask, stock_len - 1, _VAL[drawn_cid]))
|
||
|
|
|
||
|
|
for ns in next_states:
|
||
|
|
if ns[0] == 0:
|
||
|
|
return TriPeaksSolveReport(True, nodes, hardness)
|
||
|
|
if ns not in visited:
|
||
|
|
visited.add(ns)
|
||
|
|
counter += 1
|
||
|
|
h = ns[0].bit_count() * 4 + (23 - ns[1])
|
||
|
|
heapq.heappush(pq, (h + depth // 4, depth + 1, counter, ns))
|
||
|
|
else:
|
||
|
|
b_mask, stock_t, waste_t, redeals_rem = state
|
||
|
|
if b_mask == 0:
|
||
|
|
return TriPeaksSolveReport(True, nodes, hardness)
|
||
|
|
exposed = _exposed_indices(b_mask)
|
||
|
|
top_val = _VAL[waste_t[-1]]
|
||
|
|
next_states = []
|
||
|
|
|
||
|
|
for idx in exposed:
|
||
|
|
cid = board_ids[idx]
|
||
|
|
if is_tripeaks_adjacent_val(_VAL[cid], top_val):
|
||
|
|
next_states.append((b_mask & ~(1 << idx), stock_t, waste_t + (cid,), redeals_rem))
|
||
|
|
|
||
|
|
if stock_t:
|
||
|
|
next_states.append((b_mask, stock_t[:-1], waste_t + (stock_t[-1],), redeals_rem))
|
||
|
|
elif len(waste_t) > 1 and redeals_rem > 0:
|
||
|
|
# Redeal: Waste umdrehen, erste Karte sofort als neue offene Ablagekarte aufdecken
|
||
|
|
recycled = list(reversed(waste_t))
|
||
|
|
new_first = recycled.pop()
|
||
|
|
next_states.append((b_mask, tuple(recycled), (new_first,), redeals_rem - 1))
|
||
|
|
|
||
|
|
for ns in next_states:
|
||
|
|
if ns[0] == 0:
|
||
|
|
return TriPeaksSolveReport(True, nodes, hardness)
|
||
|
|
if ns not in visited:
|
||
|
|
visited.add(ns)
|
||
|
|
counter += 1
|
||
|
|
h = ns[0].bit_count() * 4 - ns[3] * 3
|
||
|
|
heapq.heappush(pq, (h + depth // 4, depth + 1, counter, ns))
|
||
|
|
|
||
|
|
return TriPeaksSolveReport(False, nodes, hardness)
|
||
|
|
|
||
|
|
|
||
|
|
def generate_solvable_tripeaks_deal(
|
||
|
|
difficulty: int = 1,
|
||
|
|
seed: int | None = None,
|
||
|
|
) -> tuple[list[SolitaireCard | None], list[SolitaireCard], list[SolitaireCard]]:
|
||
|
|
"""
|
||
|
|
Erzeugt ein garantiert lösbares TriPeaks-Deck (28er Tableau, 23er Talon, 1 Start-Waste)
|
||
|
|
passend zur Schwierigkeit (0..3 -> 2 / 1 / 0 / 0 Redeals).
|
||
|
|
"""
|
||
|
|
rng = random.Random(seed) if seed is not None else random.Random()
|
||
|
|
diff = max(0, min(3, int(difficulty)))
|
||
|
|
max_redeals = TRIPEAKS_REDEALS_BY_DIFF.get(diff, 1)
|
||
|
|
|
||
|
|
targets = {0: -4.0, 1: 8.0, 2: 14.0, 3: 28.0}
|
||
|
|
target = targets[diff]
|
||
|
|
node_budget = 3000 if diff <= 1 else 4800
|
||
|
|
|
||
|
|
base_deck = list(range(52))
|
||
|
|
candidates: list[tuple[float, list[int]]] = []
|
||
|
|
|
||
|
|
for _attempt in range(320):
|
||
|
|
trial = list(base_deck)
|
||
|
|
rng.shuffle(trial)
|
||
|
|
report = solve_tripeaks_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 <= 18.0:
|
||
|
|
break
|
||
|
|
if diff == 2 and 10.0 <= composite <= 24.0 and len(candidates) >= 2:
|
||
|
|
break
|
||
|
|
if diff == 3 and composite >= 22.0 and len(candidates) >= 2:
|
||
|
|
break
|
||
|
|
if len(candidates) >= 4:
|
||
|
|
break
|
||
|
|
|
||
|
|
while not candidates:
|
||
|
|
trial = list(base_deck)
|
||
|
|
rng.shuffle(trial)
|
||
|
|
report = solve_tripeaks_deal(trial, max_redeals=max_redeals, max_nodes=6000)
|
||
|
|
if report.solvable:
|
||
|
|
candidates.append((report.layout_hardness + report.nodes_expanded / 45.0, trial))
|
||
|
|
|
||
|
|
if diff == 3:
|
||
|
|
best = max(candidates, key=lambda x: x[0])[1]
|
||
|
|
elif diff == 0:
|
||
|
|
best = min(candidates, key=lambda x: x[0])[1]
|
||
|
|
else:
|
||
|
|
best = min(candidates, key=lambda x: abs(x[0] - target))[1]
|
||
|
|
|
||
|
|
# Reihen 0..2 (Indices 0..17) starten verdeckt, Reihe 3 (Indices 18..27) startet offen!
|
||
|
|
board: list[SolitaireCard | None] = [
|
||
|
|
_decode_card(best[i], face_up=(i >= 18)) for i in range(28)
|
||
|
|
]
|
||
|
|
waste = [_decode_card(best[28], face_up=True)]
|
||
|
|
stock = [_decode_card(cid, face_up=False) for cid in best[29:]]
|
||
|
|
return board, stock, waste
|