the_goth_cardgame_collection/games/solitaire/freecell/models/freecell_engine.py

461 lines
18 KiB
Python

# -*- coding: utf-8 -*-
# games/solitaire/freecell/models/freecell_engine.py
from __future__ import annotations
from games.solitaire.base.solitaire_core import (
SolitaireBaseEngine,
SolitaireCard,
is_alternating_descending,
)
from games.solitaire.freecell.models.freecell_solver import generate_solvable_freecell_columns
from resources.code_res.game_constants import SUITS
class FreeCellEngine(SolitaireBaseEngine):
"""
Vollständige FreeCell-Spiellogik:
- 8 Tableau-Spalten (4x 7 Karten, 4x 6 Karten, alle offen)
- 4 Freie Zellen (je max. 1 Karte)
- 4 Foundations (fest nach SUITS geordnet)
- Supermove-Formel: max_cards = (empty_freecells + 1) * (2 ** empty_aux_columns)
"""
NUM_TABLEAU = 8
NUM_FREECELLS = 4
NUM_FOUNDATIONS = 4
SCORE_TO_FOUNDATION = 10
SCORE_FOUNDATION_BACK = -15
def __init__(self, difficulty: int = 1, seed: int | None = None):
super().__init__()
self.difficulty: int = max(0, min(3, int(difficulty)))
self.seed: int | None = seed
self.freecells: list[SolitaireCard | None] = [None] * self.NUM_FREECELLS
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(difficulty=self.difficulty, seed=seed)
def new_game(self, difficulty: int | None = None, seed: int | None = None):
if difficulty is not None:
self.difficulty = max(0, min(3, int(difficulty)))
self.seed = seed
self.reset_tracking()
self.freecells = [None] * self.NUM_FREECELLS
self.foundations = [[] for _ in range(self.NUM_FOUNDATIONS)]
self.tableau = generate_solvable_freecell_columns(difficulty=self.difficulty, seed=seed)
self.capture_initial_state()
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
# --- Kapazität & Regel-Prüfungen ---
def foundation_index_for_suit(self, suit: str) -> int:
return SUITS.index(suit)
@property
def empty_freecell_count(self) -> int:
return sum(1 for c in self.freecells if c is None)
@property
def empty_tableau_count(self) -> int:
return sum(1 for col in self.tableau if not col)
def max_movable_cards(self, target_is_empty_tableau: bool = False) -> int:
"""
Klassische FreeCell-Supermove-Kapazität:
(freie Zellen + 1) * 2^(freie Hilfsspalten).
Ist die Zielspalte selbst leer, steht sie nicht als Zwischenpuffer zur Verfügung.
"""
aux_empty = self.empty_tableau_count - (1 if target_is_empty_tableau else 0)
aux_empty = max(0, aux_empty)
return (self.empty_freecell_count + 1) * (1 << aux_empty)
def can_grab_tableau_stack(self, col_idx: int, start_idx: int) -> bool:
"""Prüft, ob ab start_idx bis unten eine gültige wechselnd-absteigende Kette vorliegt."""
if not (0 <= col_idx < self.NUM_TABLEAU):
return False
col = self.tableau[col_idx]
if not (0 <= start_idx < len(col)):
return False
return is_alternating_descending(col[start_idx:])
def can_move_to_freecell(self, cell_idx: int) -> bool:
return 0 <= cell_idx < self.NUM_FREECELLS and self.freecells[cell_idx] is None
def first_empty_freecell(self) -> int | None:
for idx, c in enumerate(self.freecells):
if c is None:
return idx
return None
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
if card.suit != SUITS[found_idx]:
return False
pile = self.foundations[found_idx]
if not pile:
return card.value == 1
return card.value == pile[-1].value + 1
def check_tableau_drop(self, moving_cards: list[SolitaireCard], dst_col: int) -> tuple[bool, str]:
"""
Gibt (erlaubt, grund) zurück.
grund == 'capacity' signalisiert dem UI, dass die Reihenfolge stimmt,
aber aktuell zu wenige freie Zellen/Spalten für den Supermove offen sind.
"""
if not moving_cards or not (0 <= dst_col < self.NUM_TABLEAU):
return False, "invalid"
if not is_alternating_descending(moving_cards):
return False, "sequence"
dst = self.tableau[dst_col]
is_empty_dst = len(dst) == 0
if not is_empty_dst:
top = dst[-1]
head = moving_cards[0]
if top.is_red == head.is_red or top.value != head.value + 1:
return False, "mismatch"
cap = self.max_movable_cards(target_is_empty_tableau=is_empty_dst)
if len(moving_cards) > cap:
return False, "capacity"
return True, "ok"
def can_move_to_tableau(self, moving_cards: list[SolitaireCard], dst_col: int) -> bool:
ok, _reason = self.check_tableau_drop(moving_cards, dst_col)
return ok
# --- Aktionen: Kartenverschiebungen ---
def move_tableau_to_freecell(self, src_col: int, cell_idx: int | None = None) -> bool:
if self.won or not (0 <= src_col < self.NUM_TABLEAU) or not self.tableau[src_col]:
return False
target_cell = self.first_empty_freecell() if cell_idx is None else cell_idx
if target_cell is None or not self.can_move_to_freecell(target_cell):
return False
self.push_undo()
self.freecells[target_cell] = self.tableau[src_col].pop()
self.moves += 1
return True
def move_freecell_to_freecell(self, src_cell: int, dst_cell: int) -> bool:
if self.won or src_cell == dst_cell:
return False
if not (0 <= src_cell < self.NUM_FREECELLS and self.can_move_to_freecell(dst_cell)):
return False
if self.freecells[src_cell] is None:
return False
self.push_undo()
self.freecells[dst_cell] = self.freecells[src_cell]
self.freecells[src_cell] = None
self.moves += 1
return True
def move_freecell_to_foundation(self, src_cell: int, found_idx: int | None = None) -> bool:
if self.won or not (0 <= src_cell < self.NUM_FREECELLS):
return False
card = self.freecells[src_cell]
if card is None:
return False
target_f = self.foundation_index_for_suit(card.suit) if found_idx is None else found_idx
if not self.can_move_to_foundation(card, target_f):
return False
self.push_undo()
self.freecells[src_cell] = None
self.foundations[target_f].append(card)
self.moves += 1
self._add_score(self.SCORE_TO_FOUNDATION)
self._check_victory()
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_f = self.foundation_index_for_suit(card.suit) if found_idx is None else found_idx
if not self.can_move_to_foundation(card, target_f):
return False
self.push_undo()
self.tableau[src_col].pop()
self.foundations[target_f].append(card)
self.moves += 1
self._add_score(self.SCORE_TO_FOUNDATION)
self._check_victory()
return True
def move_freecell_to_tableau(self, src_cell: int, dst_col: int) -> bool:
if self.won or not (0 <= src_cell < self.NUM_FREECELLS):
return False
card = self.freecells[src_cell]
if card is None or not self.can_move_to_tableau([card], dst_col):
return False
self.push_undo()
self.freecells[src_cell] = None
self.tableau[dst_col].append(card)
self.moves += 1
return True
def move_tableau_to_tableau(self, src_col: int, start_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
col = self.tableau[src_col]
if not (0 <= start_idx < len(col)):
return False
moving = col[start_idx:]
if not self.can_move_to_tableau(moving, dst_col):
return False
self.push_undo()
del col[start_idx:]
self.tableau[dst_col].extend(moving)
self.moves += 1
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
pile = self.foundations[found_idx]
if not pile or not self.can_move_to_tableau([pile[-1]], dst_col):
return False
self.push_undo()
card = pile.pop()
self.tableau[dst_col].append(card)
self.moves += 1
self._add_score(self.SCORE_FOUNDATION_BACK)
return True
def move_foundation_to_freecell(self, found_idx: int, cell_idx: int) -> bool:
if self.won or not (0 <= found_idx < self.NUM_FOUNDATIONS):
return False
pile = self.foundations[found_idx]
if not pile or not self.can_move_to_freecell(cell_idx):
return False
self.push_undo()
self.freecells[cell_idx] = pile.pop()
self.moves += 1
self._add_score(self.SCORE_FOUNDATION_BACK)
return True
# --- Komfort: Auto-Complete, Hinweise & Sackgassen-Prüfung ---
def can_auto_complete(self) -> bool:
"""
Aktiv, sobald jede Tableau-Spalte für sich monoton fallend sortiert ist
(keine kleinere Karte mehr unter einer größeren Karte eingeklemmt).
"""
if self.won:
return False
for col in self.tableau:
for i in range(len(col) - 1):
if col[i].value < col[i + 1].value:
return False
return True
def auto_complete_step(self, record_undo: bool = False) -> bool:
if self.won:
return False
candidates: list[tuple[int, str, int, int]] = []
for fc_i, c in enumerate(self.freecells):
if c is not None:
f_idx = self.foundation_index_for_suit(c.suit)
if self.can_move_to_foundation(c, f_idx):
candidates.append((c.value, "freecell", fc_i, f_idx))
for col_i, col in enumerate(self.tableau):
if col:
c = col[-1]
f_idx = self.foundation_index_for_suit(c.suit)
if self.can_move_to_foundation(c, f_idx):
candidates.append((c.value, "tableau", col_i, f_idx))
if not candidates:
return False
candidates.sort(key=lambda item: item[0])
_val, zone, src_idx, f_idx = candidates[0]
if record_undo:
self.push_undo()
if zone == "freecell":
card = self.freecells[src_idx]
self.freecells[src_idx] = None
else:
card = self.tableau[src_idx].pop()
assert card is not None
self.foundations[f_idx].append(card)
self.moves += 1
self._add_score(self.SCORE_TO_FOUNDATION)
self._check_victory()
return True
def has_any_meaningful_move(self) -> bool:
"""
Erkennt echte FreeCell-Deadlocks (alle 4 FreeCells voll, keine leere Spalte,
keine Karte passt auf Foundation oder eine andere Tableau-Spitze).
"""
if self.won:
return True
# Sobald mindestens eine FreeCell frei ist oder eine Spalte leer ist, kann noch rangiert werden
if self.empty_freecell_count > 0 or self.empty_tableau_count > 0:
return True
# 1. Irgendeine FreeCell- oder Tableau-Karte auf Foundation?
for c in self.freecells:
if c is not None and self.can_move_to_foundation(c, self.foundation_index_for_suit(c.suit)):
return True
for col in self.tableau:
if col and self.can_move_to_foundation(col[-1], self.foundation_index_for_suit(col[-1].suit)):
return True
# 2. FreeCell -> belegte Tableau-Spalte?
for fc_i, c in enumerate(self.freecells):
if c is not None:
for dst_col in range(self.NUM_TABLEAU):
if self.can_move_to_tableau([c], dst_col):
return True
# 3. Tableau -> belegte Tableau-Spalte? (bei 0 freien Zellen/Spalten ist Kapazität = 1, also nur Einzelspitze)
for src_col, col in enumerate(self.tableau):
if not col:
continue
top = col[-1]
# Verhindere reines Hin-und-Her derselben Karte zwischen zwei gleichwertigen Elternkarten,
# außer darunter liegt eine andere Karte, die dadurch spielbar wird.
for dst_col in range(self.NUM_TABLEAU):
if src_col != dst_col and self.can_move_to_tableau([top], dst_col):
if len(col) >= 2:
prev_parent = col[-2]
new_parent = self.tableau[dst_col][-1]
# Wenn Karte schon auf gültigem Gegenfarben-Elternteil liegt (z.B. schwarze 7 auf roter 8)
# und nur auf die andere rote 8 wechselt, prüfen ob prev_parent danach selbst wohin kann
if prev_parent.is_red != top.is_red and prev_parent.value == top.value + 1:
can_use_exposed = self.can_move_to_foundation(
prev_parent, self.foundation_index_for_suit(prev_parent.suit)
) or any(
c_i != src_col and c_i != dst_col and self.can_move_to_tableau([prev_parent], c_i)
for c_i in range(self.NUM_TABLEAU)
)
if not can_use_exposed:
continue
return True
return False
def get_hint(self) -> dict | None:
# 1. Direkt auf Foundation
for fc_i, c in enumerate(self.freecells):
if c is not None:
f_idx = self.foundation_index_for_suit(c.suit)
if self.can_move_to_foundation(c, f_idx):
return {"type": "fc_to_foundation", "src_cell": fc_i, "dst": f_idx}
for col_i, col in enumerate(self.tableau):
if col:
c = col[-1]
f_idx = self.foundation_index_for_suit(c.suit)
if self.can_move_to_foundation(c, f_idx):
return {"type": "tab_to_foundation", "src_col": col_i, "dst": f_idx}
# 2. FreeCell zurück ins Tableau auf passende Karte
for fc_i, c in enumerate(self.freecells):
if c is not None:
for dst_col in range(self.NUM_TABLEAU):
if self.tableau[dst_col] and self.can_move_to_tableau([c], dst_col):
return {"type": "fc_to_tableau", "src_cell": fc_i, "dst_col": dst_col}
# 3. Geordneten Run im Tableau auf eine nicht-leere Zielspalte legen (verlängert Sequenz / legt frei)
for src_col, col in enumerate(self.tableau):
if not col:
continue
# Längsten geordneten Run ab Spaltenende bestimmen
run_start = len(col) - 1
while run_start > 0 and is_alternating_descending(col[run_start - 1 :]):
run_start -= 1
moving = col[run_start:]
for dst_col in range(self.NUM_TABLEAU):
if src_col != dst_col and self.tableau[dst_col] and self.can_move_to_tableau(moving, dst_col):
return {
"type": "tab_to_tableau",
"src_col": src_col,
"card_idx": run_start,
"dst_col": dst_col,
}
# 4. In leere Tableau-Spalte auslagern (wenn dadurch Karten darunter frei werden)
empty_cols = [i for i, col in enumerate(self.tableau) if not col]
if empty_cols:
dst_empty = empty_cols[0]
for src_col, col in enumerate(self.tableau):
if len(col) <= 1:
continue
run_start = len(col) - 1
while run_start > 0 and is_alternating_descending(col[run_start - 1 :]):
run_start -= 1
if run_start > 0 and self.can_move_to_tableau(col[run_start:], dst_empty):
return {
"type": "tab_to_tableau",
"src_col": src_col,
"card_idx": run_start,
"dst_col": dst_empty,
}
# 5. Karte in freie Zelle parken (bevorzugt Spalten, in denen direkt darunter ein Ass/niedriger Wert liegt)
free_cell = self.first_empty_freecell()
if free_cell is not None:
best_col: int | None = None
best_val = 99
for col_i, col in enumerate(self.tableau):
if len(col) >= 2 and col[-2].value < best_val:
best_val = col[-2].value
best_col = col_i
if best_col is None:
best_col = next((i for i, col in enumerate(self.tableau) if col), None)
if best_col is not None:
return {"type": "tab_to_fc", "src_col": best_col, "dst_cell": free_cell}
return None
# --- Persistenz ---
def serialize_board(self) -> dict:
return {
"difficulty": self.difficulty,
"freecells": [c.to_dict() if c is not None else None for c in self.freecells],
"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.difficulty = max(0, min(3, int(board.get("difficulty", 1))))
self.freecells = [
SolitaireCard.from_dict(d) if d is not None else None
for d in board["freecells"]
]
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"]
]