Skip to content

patiencepilot

patiencepilot

Public patiencepilot API.

PatiencePilotApp dataclass

Small application service for UI and adapter workflows.

Source code in src/patiencepilot/app.py
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
@dataclass(slots=True)
class PatiencePilotApp:
    """Small application service for UI and adapter workflows."""

    variant: str = "klondike"
    options: dict[str, object] = field(default_factory=dict)
    session: GameSession | None = None
    advice_provider: AdviceProvider | None = None

    def select_variant(self, name: str, options: VariantOptions | None = None) -> Variant:
        """Select the variant used for newly created sessions.

        Args:
            name: Registered variant name.
            options: Variant-specific option values.
        """
        rules = resolve_variant(name, options)
        self.variant = rules.name
        self.options = {} if options is None else dict(options)
        return rules

    def select_solver(self, name: str = "dummy") -> AdviceProvider:
        """Select the advice provider used for future advice requests.

        Args:
            name: Registered solver name or alias.
        """
        self.advice_provider = resolve_solver(name)
        return self.advice_provider

    def new_session(
        self,
        *,
        seed: Seed = None,
        metadata: Mapping[str, object] | None = None,
        ui_state: Mapping[str, object] | None = None,
    ) -> GameSession:
        """Create, store, and return a new session for the selected variant."""
        self.session = GameSession.new(
            self.variant,
            seed=seed,
            options=self.options,
            metadata=metadata,
            ui_state=ui_state,
        )
        return self.session

    def use_session(self, session: GameSession) -> GameSession:
        """Store an existing session and sync selected variant metadata."""
        session.validate_state()
        self.session = session
        self.variant = session.state.variant
        self.options = variant_options_from_state(session.state)
        return session

    def validate(self, state: GameState | None = None) -> ValidationReport:
        """Validate a state or the active session state without raising."""
        try:
            if state is not None:
                resolve_variant(state.variant, variant_options_from_state(state)).validate_state(state)
            else:
                self._require_session().validate_state()
        except PatiencePilotError as error:
            return _validation_report("state", error)
        return ValidationReport(ok=True)

    def apply_move(self, move: Move) -> MoveResult:
        """Apply ``move`` to the active session."""
        return self._require_session().apply_move(move)

    def undo(self) -> GameSession:
        """Undo the active session's most recent move and return the session."""
        session = self._require_session()
        session.undo()
        return session

    def redo(self) -> MoveResult:
        """Redo the active session's most recently undone move."""
        return self._require_session().redo()

    def export_session(
        self,
        session: GameSession | None = None,
        *,
        seen_cards: Iterable[Card] | None = None,
    ) -> SerializedSession:
        """Return a serialized payload for ``session`` or the active session."""
        return export_session(self._require_session() if session is None else session, seen_cards=seen_cards)

    def import_session(self, data: Mapping[str, object]) -> GameSession:
        """Import, store, and return a session payload."""
        session = import_session(data)
        self.use_session(session)
        return session

    def request_advice(
        self,
        *,
        provider: AdviceProvider | None = None,
        limit: SearchLimit | None = None,
        seen_cards: Iterable[Card] | None = None,
    ) -> Advice:
        """Request advice for the active session from an advice provider.

        Args:
            provider: Optional provider to use for this request. When omitted,
                the configured ``advice_provider`` is used.
            limit: Optional solver search limits.
            seen_cards: Optional cards known from earlier observation history.
        """
        selected_provider = self.advice_provider if provider is None else provider
        if selected_provider is None:
            msg = "no advice provider configured"
            raise InvalidStateError(msg)
        session = self._require_session()
        view = PlayerView.from_state(session.state, seen_cards=_seen_cards_for_session(session, seen_cards))
        return selected_provider.suggest(view, limit=limit)

    def _require_session(self) -> GameSession:
        """Return the active session or raise a package error."""
        if self.session is None:
            msg = "no active session"
            raise InvalidStateError(msg)
        return self.session

select_variant

select_variant(
    name: str, options: VariantOptions | None = None
) -> Variant

Select the variant used for newly created sessions.

Parameters:

Name Type Description Default
name str

Registered variant name.

required
options VariantOptions | None

Variant-specific option values.

None
Source code in src/patiencepilot/app.py
72
73
74
75
76
77
78
79
80
81
82
def select_variant(self, name: str, options: VariantOptions | None = None) -> Variant:
    """Select the variant used for newly created sessions.

    Args:
        name: Registered variant name.
        options: Variant-specific option values.
    """
    rules = resolve_variant(name, options)
    self.variant = rules.name
    self.options = {} if options is None else dict(options)
    return rules

select_solver

select_solver(name: str = 'dummy') -> AdviceProvider

Select the advice provider used for future advice requests.

Parameters:

Name Type Description Default
name str

Registered solver name or alias.

'dummy'
Source code in src/patiencepilot/app.py
84
85
86
87
88
89
90
91
def select_solver(self, name: str = "dummy") -> AdviceProvider:
    """Select the advice provider used for future advice requests.

    Args:
        name: Registered solver name or alias.
    """
    self.advice_provider = resolve_solver(name)
    return self.advice_provider

new_session

new_session(
    *,
    seed: Seed = None,
    metadata: Mapping[str, object] | None = None,
    ui_state: Mapping[str, object] | None = None,
) -> GameSession

Create, store, and return a new session for the selected variant.

Source code in src/patiencepilot/app.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
def new_session(
    self,
    *,
    seed: Seed = None,
    metadata: Mapping[str, object] | None = None,
    ui_state: Mapping[str, object] | None = None,
) -> GameSession:
    """Create, store, and return a new session for the selected variant."""
    self.session = GameSession.new(
        self.variant,
        seed=seed,
        options=self.options,
        metadata=metadata,
        ui_state=ui_state,
    )
    return self.session

use_session

use_session(session: GameSession) -> GameSession

Store an existing session and sync selected variant metadata.

Source code in src/patiencepilot/app.py
110
111
112
113
114
115
116
def use_session(self, session: GameSession) -> GameSession:
    """Store an existing session and sync selected variant metadata."""
    session.validate_state()
    self.session = session
    self.variant = session.state.variant
    self.options = variant_options_from_state(session.state)
    return session

validate

validate(
    state: GameState | None = None,
) -> ValidationReport

Validate a state or the active session state without raising.

Source code in src/patiencepilot/app.py
118
119
120
121
122
123
124
125
126
127
def validate(self, state: GameState | None = None) -> ValidationReport:
    """Validate a state or the active session state without raising."""
    try:
        if state is not None:
            resolve_variant(state.variant, variant_options_from_state(state)).validate_state(state)
        else:
            self._require_session().validate_state()
    except PatiencePilotError as error:
        return _validation_report("state", error)
    return ValidationReport(ok=True)

apply_move

apply_move(move: Move) -> MoveResult

Apply move to the active session.

Source code in src/patiencepilot/app.py
129
130
131
def apply_move(self, move: Move) -> MoveResult:
    """Apply ``move`` to the active session."""
    return self._require_session().apply_move(move)

undo

undo() -> GameSession

Undo the active session's most recent move and return the session.

Source code in src/patiencepilot/app.py
133
134
135
136
137
def undo(self) -> GameSession:
    """Undo the active session's most recent move and return the session."""
    session = self._require_session()
    session.undo()
    return session

redo

redo() -> MoveResult

Redo the active session's most recently undone move.

Source code in src/patiencepilot/app.py
139
140
141
def redo(self) -> MoveResult:
    """Redo the active session's most recently undone move."""
    return self._require_session().redo()

export_session

export_session(
    session: GameSession | None = None,
    *,
    seen_cards: Iterable[Card] | None = None,
) -> SerializedSession

Return a serialized payload for session or the active session.

Source code in src/patiencepilot/app.py
143
144
145
146
147
148
149
150
def export_session(
    self,
    session: GameSession | None = None,
    *,
    seen_cards: Iterable[Card] | None = None,
) -> SerializedSession:
    """Return a serialized payload for ``session`` or the active session."""
    return export_session(self._require_session() if session is None else session, seen_cards=seen_cards)

import_session

import_session(data: Mapping[str, object]) -> GameSession

Import, store, and return a session payload.

Source code in src/patiencepilot/app.py
152
153
154
155
156
def import_session(self, data: Mapping[str, object]) -> GameSession:
    """Import, store, and return a session payload."""
    session = import_session(data)
    self.use_session(session)
    return session

request_advice

request_advice(
    *,
    provider: AdviceProvider | None = None,
    limit: SearchLimit | None = None,
    seen_cards: Iterable[Card] | None = None,
) -> Advice

Request advice for the active session from an advice provider.

Parameters:

Name Type Description Default
provider AdviceProvider | None

Optional provider to use for this request. When omitted, the configured advice_provider is used.

None
limit SearchLimit | None

Optional solver search limits.

None
seen_cards Iterable[Card] | None

Optional cards known from earlier observation history.

None
Source code in src/patiencepilot/app.py
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
def request_advice(
    self,
    *,
    provider: AdviceProvider | None = None,
    limit: SearchLimit | None = None,
    seen_cards: Iterable[Card] | None = None,
) -> Advice:
    """Request advice for the active session from an advice provider.

    Args:
        provider: Optional provider to use for this request. When omitted,
            the configured ``advice_provider`` is used.
        limit: Optional solver search limits.
        seen_cards: Optional cards known from earlier observation history.
    """
    selected_provider = self.advice_provider if provider is None else provider
    if selected_provider is None:
        msg = "no advice provider configured"
        raise InvalidStateError(msg)
    session = self._require_session()
    view = PlayerView.from_state(session.state, seen_cards=_seen_cards_for_session(session, seen_cards))
    return selected_provider.suggest(view, limit=limit)

SerializedSession

Bases: TypedDict

JSON-compatible game-session payload.

Source code in src/patiencepilot/app.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class SerializedSession(TypedDict):
    """JSON-compatible game-session payload."""

    schema_version: int
    variant: str
    options: dict[str, object]
    seed: object
    initial_state: SerializedGameState
    current_state: SerializedGameState
    state_notation: str
    history: list[SerializedMove]
    redo: list[SerializedMove]
    seen_cards: list[str]
    player_view: SerializedPlayerView
    metadata: dict[str, object]
    ui_state: dict[str, object]

ValidationReport dataclass

Validation result suitable for UI display.

Source code in src/patiencepilot/app.py
53
54
55
56
57
58
59
60
@dataclass(frozen=True, slots=True)
class ValidationReport:
    """Validation result suitable for UI display."""

    ok: bool
    message: str | None = None
    error_type: str | None = None
    diagnostics: tuple[ValidationDiagnostic, ...] = ()

Card dataclass

A standard playing card.

Source code in src/patiencepilot/cards.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
@dataclass(frozen=True, slots=True)
class Card:
    """A standard playing card."""

    rank: Rank
    suit: Suit

    @property
    def color(self) -> Color:
        """Return the card color."""
        return self.suit.color

    @property
    def code(self) -> str:
        """Return the compact card code."""
        return f"{self.rank.code}{self.suit.code}"

    @classmethod
    def from_code(cls, code: str) -> Card:
        """Return the card represented by a compact code.

        Args:
            code: A rank code followed by a suit code, such as ``AS`` or
                ``10H``.

        Raises:
            ValueError: If ``code`` is not a valid card code.
        """
        normalized = code.strip().upper()
        if len(normalized) < 2:
            msg = f"card code is too short: {code!r}"
            raise ValueError(msg)
        return cls(rank=Rank.from_code(normalized[:-1]), suit=Suit.from_code(normalized[-1]))

    def __str__(self) -> str:
        """Return the compact card code."""
        return self.code

color property

color: Color

Return the card color.

code property

code: str

Return the compact card code.

from_code classmethod

from_code(code: str) -> Card

Return the card represented by a compact code.

Parameters:

Name Type Description Default
code str

A rank code followed by a suit code, such as AS or 10H.

required

Raises:

Type Description
ValueError

If code is not a valid card code.

Source code in src/patiencepilot/cards.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
@classmethod
def from_code(cls, code: str) -> Card:
    """Return the card represented by a compact code.

    Args:
        code: A rank code followed by a suit code, such as ``AS`` or
            ``10H``.

    Raises:
        ValueError: If ``code`` is not a valid card code.
    """
    normalized = code.strip().upper()
    if len(normalized) < 2:
        msg = f"card code is too short: {code!r}"
        raise ValueError(msg)
    return cls(rank=Rank.from_code(normalized[:-1]), suit=Suit.from_code(normalized[-1]))

__str__

__str__() -> str

Return the compact card code.

Source code in src/patiencepilot/cards.py
137
138
139
def __str__(self) -> str:
    """Return the compact card code."""
    return self.code

Color

Bases: Enum

A playing card color.

Source code in src/patiencepilot/cards.py
 9
10
11
12
13
class Color(Enum):
    """A playing card color."""

    RED = "red"
    BLACK = "black"

Rank

Bases: IntEnum

A playing card rank from ace through king.

Source code in src/patiencepilot/cards.py
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
class Rank(IntEnum):
    """A playing card rank from ace through king."""

    ACE = 1
    TWO = 2
    THREE = 3
    FOUR = 4
    FIVE = 5
    SIX = 6
    SEVEN = 7
    EIGHT = 8
    NINE = 9
    TEN = 10
    JACK = 11
    QUEEN = 12
    KING = 13

    @property
    def code(self) -> str:
        """Return the compact rank code."""
        return {
            Rank.ACE: "A",
            Rank.TEN: "T",
            Rank.JACK: "J",
            Rank.QUEEN: "Q",
            Rank.KING: "K",
        }.get(self, str(self.value))

    @classmethod
    def from_code(cls, code: str) -> Rank:
        """Return the rank represented by a compact code.

        Args:
            code: One of ``A``, ``2`` through ``10``, ``T``, ``J``, ``Q``, or
                ``K``.

        Raises:
            ValueError: If ``code`` is not a known rank code.
        """
        normalized = code.strip().upper()
        if normalized == "10":
            normalized = "T"
        for rank in cls:
            if rank.code == normalized:
                return rank
        msg = f"unknown rank code: {code!r}"
        raise ValueError(msg)

code property

code: str

Return the compact rank code.

from_code classmethod

from_code(code: str) -> Rank

Return the rank represented by a compact code.

Parameters:

Name Type Description Default
code str

One of A, 2 through 10, T, J, Q, or K.

required

Raises:

Type Description
ValueError

If code is not a known rank code.

Source code in src/patiencepilot/cards.py
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
@classmethod
def from_code(cls, code: str) -> Rank:
    """Return the rank represented by a compact code.

    Args:
        code: One of ``A``, ``2`` through ``10``, ``T``, ``J``, ``Q``, or
            ``K``.

    Raises:
        ValueError: If ``code`` is not a known rank code.
    """
    normalized = code.strip().upper()
    if normalized == "10":
        normalized = "T"
    for rank in cls:
        if rank.code == normalized:
            return rank
    msg = f"unknown rank code: {code!r}"
    raise ValueError(msg)

Suit

Bases: Enum

A French-suited playing card suit.

Source code in src/patiencepilot/cards.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Suit(Enum):
    """A French-suited playing card suit."""

    HEARTS = "H"
    DIAMONDS = "D"
    CLUBS = "C"
    SPADES = "S"

    @property
    def color(self) -> Color:
        """Return the suit color."""
        if self in {Suit.HEARTS, Suit.DIAMONDS}:
            return Color.RED
        return Color.BLACK

    @property
    def code(self) -> str:
        """Return the compact one-letter suit code."""
        return self.value

    @classmethod
    def from_code(cls, code: str) -> Suit:
        """Return the suit represented by a compact one-letter code.

        Args:
            code: One of ``H``, ``D``, ``C``, or ``S``.

        Raises:
            ValueError: If ``code`` is not a known suit code.
        """
        normalized = code.strip().upper()
        for suit in cls:
            if suit.code == normalized:
                return suit
        msg = f"unknown suit code: {code!r}"
        raise ValueError(msg)

color property

color: Color

Return the suit color.

code property

code: str

Return the compact one-letter suit code.

from_code classmethod

from_code(code: str) -> Suit

Return the suit represented by a compact one-letter code.

Parameters:

Name Type Description Default
code str

One of H, D, C, or S.

required

Raises:

Type Description
ValueError

If code is not a known suit code.

Source code in src/patiencepilot/cards.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
@classmethod
def from_code(cls, code: str) -> Suit:
    """Return the suit represented by a compact one-letter code.

    Args:
        code: One of ``H``, ``D``, ``C``, or ``S``.

    Raises:
        ValueError: If ``code`` is not a known suit code.
    """
    normalized = code.strip().upper()
    for suit in cls:
        if suit.code == normalized:
            return suit
    msg = f"unknown suit code: {code!r}"
    raise ValueError(msg)

InvalidMoveError

Bases: PatiencePilotError

Raised when a move is not legal from the current state.

Source code in src/patiencepilot/exceptions.py
12
13
class InvalidMoveError(PatiencePilotError):
    """Raised when a move is not legal from the current state."""

InvalidStateError

Bases: PatiencePilotError

Raised when a game state is malformed or inconsistent.

Source code in src/patiencepilot/exceptions.py
8
9
class InvalidStateError(PatiencePilotError):
    """Raised when a game state is malformed or inconsistent."""

NotationError

Bases: PatiencePilotError

Raised when state notation cannot be parsed or serialized.

Source code in src/patiencepilot/exceptions.py
28
29
class NotationError(PatiencePilotError):
    """Raised when state notation cannot be parsed or serialized."""

PatiencePilotError

Bases: Exception

Base class for patiencepilot errors.

Source code in src/patiencepilot/exceptions.py
4
5
class PatiencePilotError(Exception):
    """Base class for patiencepilot errors."""

SolverLimitError

Bases: PatiencePilotError

Raised when a solver cannot continue within configured limits.

Source code in src/patiencepilot/exceptions.py
24
25
class SolverLimitError(PatiencePilotError):
    """Raised when a solver cannot continue within configured limits."""

UnsupportedSolverError

Bases: PatiencePilotError

Raised when a solver is not supported.

Source code in src/patiencepilot/exceptions.py
20
21
class UnsupportedSolverError(PatiencePilotError):
    """Raised when a solver is not supported."""

UnsupportedVariantError

Bases: PatiencePilotError

Raised when a Solitaire variant is not supported.

Source code in src/patiencepilot/exceptions.py
16
17
class UnsupportedVariantError(PatiencePilotError):
    """Raised when a Solitaire variant is not supported."""

GameSession dataclass

Thin mutable wrapper around pure engine state transitions.

Source code in src/patiencepilot/game.py
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
@dataclass(slots=True)
class GameSession:
    """Thin mutable wrapper around pure engine state transitions."""

    state: GameState
    variant: Variant | str | None = None
    seed: Seed = None
    metadata: dict[str, object] = field(default_factory=dict)
    ui_state: dict[str, object] = field(default_factory=dict)
    _history: list[SessionStep] = field(default_factory=list, init=False, repr=False)
    _redo_stack: list[SessionStep] = field(default_factory=list, init=False, repr=False)

    def __post_init__(self) -> None:
        """Validate the starting state."""
        engine.validate_state(self.state, self.variant)

    @classmethod
    def new(
        cls,
        variant: Variant | str | None = None,
        *,
        seed: Seed = None,
        options: VariantOptions | None = None,
        metadata: Mapping[str, object] | None = None,
        ui_state: Mapping[str, object] | None = None,
    ) -> GameSession:
        """Return a session around a newly dealt game.

        Args:
            variant: Rule set or registered variant name to use. Defaults to
                Klondike draw-one with unlimited redeals.
            seed: Optional deterministic random seed.
            options: Variant options when ``variant`` is a name or omitted.
            metadata: Optional session metadata for callers or persistence.
            ui_state: Optional UI-only state for adapters.
        """
        state = engine.new_game(variant, seed=seed, options=options)
        return cls(
            state=state,
            variant=variant,
            seed=seed,
            metadata={} if metadata is None else dict(metadata),
            ui_state={} if ui_state is None else dict(ui_state),
        )

    @property
    def history(self) -> tuple[SessionStep, ...]:
        """Return applied session steps in order."""
        return tuple(self._history)

    @property
    def redo_history(self) -> tuple[SessionStep, ...]:
        """Return undone session steps available for redo, oldest first."""
        return tuple(reversed(self._redo_stack))

    @property
    def move_history(self) -> tuple[Move, ...]:
        """Return moves applied in this session."""
        return tuple(step.move for step in self._history)

    @property
    def result_history(self) -> tuple[MoveResult, ...]:
        """Return move results applied in this session."""
        return tuple(step.result for step in self._history)

    @property
    def last_result(self) -> MoveResult | None:
        """Return the most recent move result, if any."""
        if not self._history:
            return None
        return self._history[-1].result

    @property
    def can_undo(self) -> bool:
        """Return whether the session has a move to undo."""
        return bool(self._history)

    @property
    def can_redo(self) -> bool:
        """Return whether the session has a move to redo."""
        return bool(self._redo_stack)

    def legal_moves(self) -> tuple[Move, ...]:
        """Return legal moves from the current state."""
        return engine.legal_moves(self.state, self.variant)

    def validate_state(self) -> None:
        """Validate the current state."""
        engine.validate_state(self.state, self.variant)

    def is_won(self) -> bool:
        """Return whether the current state is won."""
        return engine.is_won(self.state, self.variant)

    def apply_move(self, move: Move) -> MoveResult:
        """Apply ``move`` to the current state and record history.

        Args:
            move: Move to apply.
        """
        before = self.state
        result = engine.apply_move(before, move, self.variant)
        self.state = result.state
        self._history.append(SessionStep(move=move, before=before, result=result))
        self._redo_stack.clear()
        return result

    def undo(self) -> SessionStep:
        """Undo the most recent move.

        Raises:
            InvalidMoveError: If there is no move to undo.
        """
        if not self._history:
            msg = "no moves to undo"
            raise InvalidMoveError(msg)

        step = self._history.pop()
        self.state = step.before
        self._redo_stack.append(step)
        return step

    def redo(self) -> MoveResult:
        """Redo the most recently undone move.

        Raises:
            InvalidMoveError: If there is no move to redo.
        """
        if not self._redo_stack:
            msg = "no moves to redo"
            raise InvalidMoveError(msg)

        undone_step = self._redo_stack.pop()
        before = self.state
        result = engine.apply_move(before, undone_step.move, self.variant)
        self.state = result.state
        self._history.append(SessionStep(move=undone_step.move, before=before, result=result))
        return result

    def clear_history(self) -> None:
        """Clear undo and redo history without changing the current state."""
        self._history.clear()
        self._redo_stack.clear()

history property

history: tuple[SessionStep, ...]

Return applied session steps in order.

redo_history property

redo_history: tuple[SessionStep, ...]

Return undone session steps available for redo, oldest first.

move_history property

move_history: tuple[Move, ...]

Return moves applied in this session.

result_history property

result_history: tuple[MoveResult, ...]

Return move results applied in this session.

last_result property

last_result: MoveResult | None

Return the most recent move result, if any.

can_undo property

can_undo: bool

Return whether the session has a move to undo.

can_redo property

can_redo: bool

Return whether the session has a move to redo.

__post_init__

__post_init__() -> None

Validate the starting state.

Source code in src/patiencepilot/game.py
43
44
45
def __post_init__(self) -> None:
    """Validate the starting state."""
    engine.validate_state(self.state, self.variant)

new classmethod

new(
    variant: Variant | str | None = None,
    *,
    seed: Seed = None,
    options: VariantOptions | None = None,
    metadata: Mapping[str, object] | None = None,
    ui_state: Mapping[str, object] | None = None,
) -> GameSession

Return a session around a newly dealt game.

Parameters:

Name Type Description Default
variant Variant | str | None

Rule set or registered variant name to use. Defaults to Klondike draw-one with unlimited redeals.

None
seed Seed

Optional deterministic random seed.

None
options VariantOptions | None

Variant options when variant is a name or omitted.

None
metadata Mapping[str, object] | None

Optional session metadata for callers or persistence.

None
ui_state Mapping[str, object] | None

Optional UI-only state for adapters.

None
Source code in src/patiencepilot/game.py
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
@classmethod
def new(
    cls,
    variant: Variant | str | None = None,
    *,
    seed: Seed = None,
    options: VariantOptions | None = None,
    metadata: Mapping[str, object] | None = None,
    ui_state: Mapping[str, object] | None = None,
) -> GameSession:
    """Return a session around a newly dealt game.

    Args:
        variant: Rule set or registered variant name to use. Defaults to
            Klondike draw-one with unlimited redeals.
        seed: Optional deterministic random seed.
        options: Variant options when ``variant`` is a name or omitted.
        metadata: Optional session metadata for callers or persistence.
        ui_state: Optional UI-only state for adapters.
    """
    state = engine.new_game(variant, seed=seed, options=options)
    return cls(
        state=state,
        variant=variant,
        seed=seed,
        metadata={} if metadata is None else dict(metadata),
        ui_state={} if ui_state is None else dict(ui_state),
    )

legal_moves

legal_moves() -> tuple[Move, ...]

Return legal moves from the current state.

Source code in src/patiencepilot/game.py
113
114
115
def legal_moves(self) -> tuple[Move, ...]:
    """Return legal moves from the current state."""
    return engine.legal_moves(self.state, self.variant)

validate_state

validate_state() -> None

Validate the current state.

Source code in src/patiencepilot/game.py
117
118
119
def validate_state(self) -> None:
    """Validate the current state."""
    engine.validate_state(self.state, self.variant)

is_won

is_won() -> bool

Return whether the current state is won.

Source code in src/patiencepilot/game.py
121
122
123
def is_won(self) -> bool:
    """Return whether the current state is won."""
    return engine.is_won(self.state, self.variant)

apply_move

apply_move(move: Move) -> MoveResult

Apply move to the current state and record history.

Parameters:

Name Type Description Default
move Move

Move to apply.

required
Source code in src/patiencepilot/game.py
125
126
127
128
129
130
131
132
133
134
135
136
def apply_move(self, move: Move) -> MoveResult:
    """Apply ``move`` to the current state and record history.

    Args:
        move: Move to apply.
    """
    before = self.state
    result = engine.apply_move(before, move, self.variant)
    self.state = result.state
    self._history.append(SessionStep(move=move, before=before, result=result))
    self._redo_stack.clear()
    return result

undo

undo() -> SessionStep

Undo the most recent move.

Raises:

Type Description
InvalidMoveError

If there is no move to undo.

Source code in src/patiencepilot/game.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
def undo(self) -> SessionStep:
    """Undo the most recent move.

    Raises:
        InvalidMoveError: If there is no move to undo.
    """
    if not self._history:
        msg = "no moves to undo"
        raise InvalidMoveError(msg)

    step = self._history.pop()
    self.state = step.before
    self._redo_stack.append(step)
    return step

redo

redo() -> MoveResult

Redo the most recently undone move.

Raises:

Type Description
InvalidMoveError

If there is no move to redo.

Source code in src/patiencepilot/game.py
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
def redo(self) -> MoveResult:
    """Redo the most recently undone move.

    Raises:
        InvalidMoveError: If there is no move to redo.
    """
    if not self._redo_stack:
        msg = "no moves to redo"
        raise InvalidMoveError(msg)

    undone_step = self._redo_stack.pop()
    before = self.state
    result = engine.apply_move(before, undone_step.move, self.variant)
    self.state = result.state
    self._history.append(SessionStep(move=undone_step.move, before=before, result=result))
    return result

clear_history

clear_history() -> None

Clear undo and redo history without changing the current state.

Source code in src/patiencepilot/game.py
170
171
172
173
def clear_history(self) -> None:
    """Clear undo and redo history without changing the current state."""
    self._history.clear()
    self._redo_stack.clear()

SessionStep dataclass

One move applied within a game session.

Source code in src/patiencepilot/game.py
17
18
19
20
21
22
23
24
25
26
27
28
@dataclass(frozen=True, slots=True)
class SessionStep:
    """One move applied within a game session."""

    move: Move
    before: GameState
    result: MoveResult

    @property
    def after(self) -> GameState:
        """Return the state after the move was applied."""
        return self.result.state

after property

after: GameState

Return the state after the move was applied.

DrawFromStock dataclass

Draw one or more cards from stock to waste.

Source code in src/patiencepilot/moves.py
40
41
42
@dataclass(frozen=True, slots=True)
class DrawFromStock:
    """Draw one or more cards from stock to waste."""

DrewStockCards dataclass

Effect describing cards drawn from stock to waste.

Source code in src/patiencepilot/moves.py
72
73
74
75
76
@dataclass(frozen=True, slots=True)
class DrewStockCards:
    """Effect describing cards drawn from stock to waste."""

    cards: tuple[Card, ...]

MovedCards dataclass

Effect describing cards moved between locations.

Source code in src/patiencepilot/moves.py
55
56
57
58
59
60
61
@dataclass(frozen=True, slots=True)
class MovedCards:
    """Effect describing cards moved between locations."""

    cards: tuple[Card, ...]
    source: str
    destination: str

MoveResult dataclass

The result of applying a legal move.

Source code in src/patiencepilot/moves.py
89
90
91
92
93
94
95
@dataclass(frozen=True, slots=True)
class MoveResult:
    """The result of applying a legal move."""

    move: Move
    state: GameState
    effects: tuple[MoveEffect, ...] = ()

RecycledWaste dataclass

Effect describing waste cards recycled into stock.

Source code in src/patiencepilot/moves.py
79
80
81
82
83
@dataclass(frozen=True, slots=True)
class RecycledWaste:
    """Effect describing waste cards recycled into stock."""

    count: int

RecycleWaste dataclass

Recycle the waste pile into stock when the rules allow it.

Source code in src/patiencepilot/moves.py
45
46
47
@dataclass(frozen=True, slots=True)
class RecycleWaste:
    """Recycle the waste pile into stock when the rules allow it."""

RevealedTableauCard dataclass

Effect describing a tableau card automatically revealed by the engine.

Source code in src/patiencepilot/moves.py
64
65
66
67
68
69
@dataclass(frozen=True, slots=True)
class RevealedTableauCard:
    """Effect describing a tableau card automatically revealed by the engine."""

    column: int
    card: Card

TableauToFoundation dataclass

Move the top visible card from a tableau column to its foundation.

Source code in src/patiencepilot/moves.py
21
22
23
24
25
@dataclass(frozen=True, slots=True)
class TableauToFoundation:
    """Move the top visible card from a tableau column to its foundation."""

    source: int

TableauToTableau dataclass

Move one or more visible cards between tableau columns.

Source code in src/patiencepilot/moves.py
12
13
14
15
16
17
18
@dataclass(frozen=True, slots=True)
class TableauToTableau:
    """Move one or more visible cards between tableau columns."""

    source: int
    destination: int
    count: int = 1

WasteToFoundation dataclass

Move the top waste card to its foundation.

Source code in src/patiencepilot/moves.py
35
36
37
@dataclass(frozen=True, slots=True)
class WasteToFoundation:
    """Move the top waste card to its foundation."""

WasteToTableau dataclass

Move the top waste card to a tableau column.

Source code in src/patiencepilot/moves.py
28
29
30
31
32
@dataclass(frozen=True, slots=True)
class WasteToTableau:
    """Move the top waste card to a tableau column."""

    destination: int

SerializedGameState

Bases: TypedDict

JSON-compatible authoritative game-state payload.

Source code in src/patiencepilot/notation.py
47
48
49
50
51
52
53
54
55
56
57
class SerializedGameState(TypedDict):
    """JSON-compatible authoritative game-state payload."""

    schema_version: int
    variant: str
    options: dict[str, object]
    foundations: list[list[str]]
    tableau: list[list[SerializedStackCard]]
    stock: list[str]
    waste: list[str]
    redeals_used: int

SerializedMove

Bases: TypedDict

JSON-compatible serialized move payload.

Source code in src/patiencepilot/notation.py
33
34
35
36
37
class SerializedMove(TypedDict):
    """JSON-compatible serialized move payload."""

    id: str
    schema_version: NotRequired[int]

SerializedPlayerStackCard

Bases: TypedDict

JSON-compatible player-view tableau card payload.

Source code in src/patiencepilot/notation.py
60
61
62
63
64
class SerializedPlayerStackCard(TypedDict):
    """JSON-compatible player-view tableau card payload."""

    card: str | None
    face_up: bool

SerializedPlayerView

Bases: TypedDict

JSON-compatible player-known state payload.

Source code in src/patiencepilot/notation.py
75
76
77
78
79
80
81
82
83
84
85
86
class SerializedPlayerView(TypedDict):
    """JSON-compatible player-known state payload."""

    schema_version: int
    variant: str
    options: dict[str, object]
    foundations: list[list[str]]
    tableau: list[list[SerializedPlayerStackCard]]
    waste: list[str]
    seen_cards: list[str]
    unknown: SerializedUnknownCardConstraints
    redeals_used: int

SerializedStackCard

Bases: TypedDict

JSON-compatible authoritative tableau card payload.

Source code in src/patiencepilot/notation.py
40
41
42
43
44
class SerializedStackCard(TypedDict):
    """JSON-compatible authoritative tableau card payload."""

    card: str
    face_up: bool

SerializedUnknownCardConstraints

Bases: TypedDict

JSON-compatible unknown-card constraint payload.

Source code in src/patiencepilot/notation.py
67
68
69
70
71
72
class SerializedUnknownCardConstraints(TypedDict):
    """JSON-compatible unknown-card constraint payload."""

    hidden_tableau_counts: list[int]
    stock_count: int
    unseen_cards: list[str]

ValidationDiagnostic dataclass

A validation diagnostic suitable for UI display.

Source code in src/patiencepilot/notation.py
89
90
91
92
93
94
95
@dataclass(frozen=True, slots=True)
class ValidationDiagnostic:
    """A validation diagnostic suitable for UI display."""

    path: str
    message: str
    error_type: str

ValidationResult dataclass

Structured validation result for notation and payload checks.

Source code in src/patiencepilot/notation.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
@dataclass(frozen=True, slots=True)
class ValidationResult:
    """Structured validation result for notation and payload checks."""

    diagnostics: tuple[ValidationDiagnostic, ...] = ()

    @property
    def ok(self) -> bool:
        """Return whether validation succeeded."""
        return not self.diagnostics

    @property
    def message(self) -> str | None:
        """Return the first validation message, if any."""
        if not self.diagnostics:
            return None
        return self.diagnostics[0].message

ok property

ok: bool

Return whether validation succeeded.

message property

message: str | None

Return the first validation message, if any.

Advice dataclass

Solver advice containing zero or more ranked move alternatives.

Source code in src/patiencepilot/solvers/base.py
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
@dataclass(frozen=True, slots=True)
class Advice:
    """Solver advice containing zero or more ranked move alternatives."""

    recommendations: tuple[RankedMove, ...]
    solver_name: str | None = None
    limit: SearchLimit | None = None
    nodes_searched: int | None = None
    depth_reached: int | None = None
    elapsed_seconds: float | None = None
    assumptions: tuple[str, ...] = ()

    def __post_init__(self) -> None:
        """Sort and validate advice metadata."""
        object.__setattr__(self, "recommendations", tuple(sorted(self.recommendations, key=lambda item: item.rank)))
        if self.nodes_searched is not None and self.nodes_searched < 0:
            msg = "nodes_searched must be non-negative"
            raise InvalidStateError(msg)
        if self.depth_reached is not None and self.depth_reached < 0:
            msg = "depth_reached must be non-negative"
            raise InvalidStateError(msg)
        if self.elapsed_seconds is not None and self.elapsed_seconds < 0:
            msg = "elapsed_seconds must be non-negative"
            raise InvalidStateError(msg)

    @classmethod
    def from_move(
        cls,
        move: Move,
        *,
        solver_name: str | None = None,
        limit: SearchLimit | None = None,
        score: float | None = None,
        confidence: float | None = None,
        reason: str | None = None,
    ) -> Advice:
        """Return advice with a single recommended move.

        Args:
            move: Recommended move.
            solver_name: Optional solver identifier.
            limit: Optional search limits used for the recommendation.
            score: Optional solver-specific move score.
            confidence: Optional confidence from 0 to 1.
            reason: Optional human-readable reason.
        """
        return cls(
            recommendations=(RankedMove(move=move, rank=1, score=score, confidence=confidence, reason=reason),),
            solver_name=solver_name,
            limit=limit,
        )

    @property
    def best(self) -> RankedMove | None:
        """Return the highest-ranked recommendation, if any."""
        if not self.recommendations:
            return None
        return self.recommendations[0]

    @property
    def best_move(self) -> Move | None:
        """Return the highest-ranked move, if any."""
        best = self.best
        if best is None:
            return None
        return best.move

    @property
    def alternatives(self) -> tuple[RankedMove, ...]:
        """Return recommendations after the best move."""
        return self.recommendations[1:]

best property

best: RankedMove | None

Return the highest-ranked recommendation, if any.

best_move property

best_move: Move | None

Return the highest-ranked move, if any.

alternatives property

alternatives: tuple[RankedMove, ...]

Return recommendations after the best move.

__post_init__

__post_init__() -> None

Sort and validate advice metadata.

Source code in src/patiencepilot/solvers/base.py
67
68
69
70
71
72
73
74
75
76
77
78
def __post_init__(self) -> None:
    """Sort and validate advice metadata."""
    object.__setattr__(self, "recommendations", tuple(sorted(self.recommendations, key=lambda item: item.rank)))
    if self.nodes_searched is not None and self.nodes_searched < 0:
        msg = "nodes_searched must be non-negative"
        raise InvalidStateError(msg)
    if self.depth_reached is not None and self.depth_reached < 0:
        msg = "depth_reached must be non-negative"
        raise InvalidStateError(msg)
    if self.elapsed_seconds is not None and self.elapsed_seconds < 0:
        msg = "elapsed_seconds must be non-negative"
        raise InvalidStateError(msg)

from_move classmethod

from_move(
    move: Move,
    *,
    solver_name: str | None = None,
    limit: SearchLimit | None = None,
    score: float | None = None,
    confidence: float | None = None,
    reason: str | None = None,
) -> Advice

Return advice with a single recommended move.

Parameters:

Name Type Description Default
move Move

Recommended move.

required
solver_name str | None

Optional solver identifier.

None
limit SearchLimit | None

Optional search limits used for the recommendation.

None
score float | None

Optional solver-specific move score.

None
confidence float | None

Optional confidence from 0 to 1.

None
reason str | None

Optional human-readable reason.

None
Source code in src/patiencepilot/solvers/base.py
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
@classmethod
def from_move(
    cls,
    move: Move,
    *,
    solver_name: str | None = None,
    limit: SearchLimit | None = None,
    score: float | None = None,
    confidence: float | None = None,
    reason: str | None = None,
) -> Advice:
    """Return advice with a single recommended move.

    Args:
        move: Recommended move.
        solver_name: Optional solver identifier.
        limit: Optional search limits used for the recommendation.
        score: Optional solver-specific move score.
        confidence: Optional confidence from 0 to 1.
        reason: Optional human-readable reason.
    """
    return cls(
        recommendations=(RankedMove(move=move, rank=1, score=score, confidence=confidence, reason=reason),),
        solver_name=solver_name,
        limit=limit,
    )

AdviceProvider

Bases: Protocol

Protocol for components that produce advice from player-known state.

Source code in src/patiencepilot/solvers/base.py
128
129
130
131
132
133
class AdviceProvider(Protocol):
    """Protocol for components that produce advice from player-known state."""

    def suggest(self, view: PlayerView, *, limit: SearchLimit | None = None) -> Advice:
        """Return move advice using only the supplied player-known view."""
        ...

suggest

suggest(
    view: PlayerView, *, limit: SearchLimit | None = None
) -> Advice

Return move advice using only the supplied player-known view.

Source code in src/patiencepilot/solvers/base.py
131
132
133
def suggest(self, view: PlayerView, *, limit: SearchLimit | None = None) -> Advice:
    """Return move advice using only the supplied player-known view."""
    ...

DummySolver dataclass

Deterministic solver that recommends the first visible legal move.

Source code in src/patiencepilot/solvers/dummy.py
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
@dataclass(frozen=True, slots=True)
class DummySolver:
    """Deterministic solver that recommends the first visible legal move."""

    name: str = "dummy"

    def suggest(self, view: PlayerView, *, limit: SearchLimit | None = None) -> Advice:
        """Return the first legal move available in ``view``.

        The solver derives legal moves only from player-visible information:
        foundations, waste, visible tableau cards, stock count, and redeal
        metadata. It does not reconstruct or inspect hidden card identities.
        """
        moves = visible_klondike_moves(view)
        if not moves:
            return Advice(recommendations=(), solver_name=self.name, limit=limit, nodes_searched=0, depth_reached=0)
        return Advice(
            recommendations=(RankedMove(move=moves[0], rank=1),),
            solver_name=self.name,
            limit=limit,
            nodes_searched=len(moves),
            depth_reached=0,
        )

suggest

suggest(
    view: PlayerView, *, limit: SearchLimit | None = None
) -> Advice

Return the first legal move available in view.

The solver derives legal moves only from player-visible information: foundations, waste, visible tableau cards, stock count, and redeal metadata. It does not reconstruct or inspect hidden card identities.

Source code in src/patiencepilot/solvers/dummy.py
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
def suggest(self, view: PlayerView, *, limit: SearchLimit | None = None) -> Advice:
    """Return the first legal move available in ``view``.

    The solver derives legal moves only from player-visible information:
    foundations, waste, visible tableau cards, stock count, and redeal
    metadata. It does not reconstruct or inspect hidden card identities.
    """
    moves = visible_klondike_moves(view)
    if not moves:
        return Advice(recommendations=(), solver_name=self.name, limit=limit, nodes_searched=0, depth_reached=0)
    return Advice(
        recommendations=(RankedMove(move=moves[0], rank=1),),
        solver_name=self.name,
        limit=limit,
        nodes_searched=len(moves),
        depth_reached=0,
    )

RankedMove dataclass

One ranked solver move recommendation.

Source code in src/patiencepilot/solvers/base.py
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
@dataclass(frozen=True, slots=True)
class RankedMove:
    """One ranked solver move recommendation."""

    move: Move
    rank: int = 1
    score: float | None = None
    confidence: float | None = None
    reason: str | None = None
    tags: tuple[str, ...] = ()

    def __post_init__(self) -> None:
        """Validate ranked-move metadata."""
        if self.rank < 1:
            msg = "rank must be at least 1"
            raise InvalidStateError(msg)
        if self.confidence is not None and not 0 <= self.confidence <= 1:
            msg = "confidence must be between 0 and 1"
            raise InvalidStateError(msg)

__post_init__

__post_init__() -> None

Validate ranked-move metadata.

Source code in src/patiencepilot/solvers/base.py
45
46
47
48
49
50
51
52
def __post_init__(self) -> None:
    """Validate ranked-move metadata."""
    if self.rank < 1:
        msg = "rank must be at least 1"
        raise InvalidStateError(msg)
    if self.confidence is not None and not 0 <= self.confidence <= 1:
        msg = "confidence must be between 0 and 1"
        raise InvalidStateError(msg)

SearchLimit dataclass

Optional limits for bounded solver work.

Source code in src/patiencepilot/solvers/base.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@dataclass(frozen=True, slots=True)
class SearchLimit:
    """Optional limits for bounded solver work."""

    time_seconds: float | None = None
    node_limit: int | None = None
    depth_limit: int | None = None

    def __post_init__(self) -> None:
        """Validate search-limit values."""
        if self.time_seconds is not None and self.time_seconds <= 0:
            msg = "time_seconds must be positive when provided"
            raise InvalidStateError(msg)
        if self.node_limit is not None and self.node_limit < 1:
            msg = "node_limit must be at least 1 when provided"
            raise InvalidStateError(msg)
        if self.depth_limit is not None and self.depth_limit < 0:
            msg = "depth_limit must be non-negative when provided"
            raise InvalidStateError(msg)

__post_init__

__post_init__() -> None

Validate search-limit values.

Source code in src/patiencepilot/solvers/base.py
21
22
23
24
25
26
27
28
29
30
31
def __post_init__(self) -> None:
    """Validate search-limit values."""
    if self.time_seconds is not None and self.time_seconds <= 0:
        msg = "time_seconds must be positive when provided"
        raise InvalidStateError(msg)
    if self.node_limit is not None and self.node_limit < 1:
        msg = "node_limit must be at least 1 when provided"
        raise InvalidStateError(msg)
    if self.depth_limit is not None and self.depth_limit < 0:
        msg = "depth_limit must be non-negative when provided"
        raise InvalidStateError(msg)

Solver

Bases: AdviceProvider, Protocol

Protocol for pluggable Solitaire solvers.

Source code in src/patiencepilot/solvers/base.py
136
137
138
139
class Solver(AdviceProvider, Protocol):
    """Protocol for pluggable Solitaire solvers."""

    name: str

SolverDefinition dataclass

Registered solver metadata and factory.

Source code in src/patiencepilot/solvers/registry.py
21
22
23
24
25
26
27
28
29
30
31
32
@dataclass(frozen=True, slots=True)
class SolverDefinition:
    """Registered solver metadata and factory."""

    name: str
    factory: SolverFactory
    aliases: tuple[str, ...] = ()
    description: str | None = None

    def create(self) -> AdviceProvider:
        """Return a new advice provider instance."""
        return self.factory()

create

create() -> AdviceProvider

Return a new advice provider instance.

Source code in src/patiencepilot/solvers/registry.py
30
31
32
def create(self) -> AdviceProvider:
    """Return a new advice provider instance."""
    return self.factory()

SolverFactory

Bases: Protocol

Callable that creates an advice provider.

Source code in src/patiencepilot/solvers/registry.py
13
14
15
16
17
18
class SolverFactory(Protocol):
    """Callable that creates an advice provider."""

    def __call__(self) -> AdviceProvider:
        """Return an advice provider instance."""
        ...

__call__

__call__() -> AdviceProvider

Return an advice provider instance.

Source code in src/patiencepilot/solvers/registry.py
16
17
18
def __call__(self) -> AdviceProvider:
    """Return an advice provider instance."""
    ...

SolverRegistry dataclass

Small immutable registry of supported solvers.

Source code in src/patiencepilot/solvers/registry.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
@dataclass(frozen=True, slots=True)
class SolverRegistry:
    """Small immutable registry of supported solvers."""

    definitions: tuple[SolverDefinition, ...]

    def __post_init__(self) -> None:
        """Validate registry keys."""
        keys: set[str] = set()
        for definition in self.definitions:
            for name in (definition.name, *definition.aliases):
                normalized = _normalize_solver_name(name)
                if normalized in keys:
                    msg = f"duplicate solver registry name: {name!r}"
                    raise InvalidStateError(msg)
                keys.add(normalized)

    @property
    def names(self) -> tuple[str, ...]:
        """Return canonical registered solver names."""
        return tuple(definition.name for definition in self.definitions)

    def register(self, definition: SolverDefinition) -> SolverRegistry:
        """Return a new registry that also contains ``definition``.

        Args:
            definition: Solver definition to add.
        """
        return SolverRegistry((*self.definitions, definition))

    def definition_for(self, name: str) -> SolverDefinition:
        """Return the registered definition for ``name`` or alias.

        Args:
            name: Solver name or alias.

        Raises:
            UnsupportedSolverError: If no solver is registered for ``name``.
        """
        normalized = _normalize_solver_name(name)
        for definition in self.definitions:
            if normalized == _normalize_solver_name(definition.name):
                return definition
            if any(normalized == _normalize_solver_name(alias) for alias in definition.aliases):
                return definition

        msg = f"unsupported solver: {name!r}"
        raise UnsupportedSolverError(msg)

    def create(self, name: str) -> AdviceProvider:
        """Return a new advice provider by solver name.

        Args:
            name: Solver name or alias.
        """
        return self.definition_for(name).create()

names property

names: tuple[str, ...]

Return canonical registered solver names.

__post_init__

__post_init__() -> None

Validate registry keys.

Source code in src/patiencepilot/solvers/registry.py
41
42
43
44
45
46
47
48
49
50
def __post_init__(self) -> None:
    """Validate registry keys."""
    keys: set[str] = set()
    for definition in self.definitions:
        for name in (definition.name, *definition.aliases):
            normalized = _normalize_solver_name(name)
            if normalized in keys:
                msg = f"duplicate solver registry name: {name!r}"
                raise InvalidStateError(msg)
            keys.add(normalized)

register

register(definition: SolverDefinition) -> SolverRegistry

Return a new registry that also contains definition.

Parameters:

Name Type Description Default
definition SolverDefinition

Solver definition to add.

required
Source code in src/patiencepilot/solvers/registry.py
57
58
59
60
61
62
63
def register(self, definition: SolverDefinition) -> SolverRegistry:
    """Return a new registry that also contains ``definition``.

    Args:
        definition: Solver definition to add.
    """
    return SolverRegistry((*self.definitions, definition))

definition_for

definition_for(name: str) -> SolverDefinition

Return the registered definition for name or alias.

Parameters:

Name Type Description Default
name str

Solver name or alias.

required

Raises:

Type Description
UnsupportedSolverError

If no solver is registered for name.

Source code in src/patiencepilot/solvers/registry.py
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def definition_for(self, name: str) -> SolverDefinition:
    """Return the registered definition for ``name`` or alias.

    Args:
        name: Solver name or alias.

    Raises:
        UnsupportedSolverError: If no solver is registered for ``name``.
    """
    normalized = _normalize_solver_name(name)
    for definition in self.definitions:
        if normalized == _normalize_solver_name(definition.name):
            return definition
        if any(normalized == _normalize_solver_name(alias) for alias in definition.aliases):
            return definition

    msg = f"unsupported solver: {name!r}"
    raise UnsupportedSolverError(msg)

create

create(name: str) -> AdviceProvider

Return a new advice provider by solver name.

Parameters:

Name Type Description Default
name str

Solver name or alias.

required
Source code in src/patiencepilot/solvers/registry.py
84
85
86
87
88
89
90
def create(self, name: str) -> AdviceProvider:
    """Return a new advice provider by solver name.

    Args:
        name: Solver name or alias.
    """
    return self.definition_for(name).create()

GameState dataclass

A complete immutable Solitaire game snapshot.

Source code in src/patiencepilot/state.py
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
@dataclass(frozen=True, slots=True)
class GameState:
    """A complete immutable Solitaire game snapshot."""

    foundations: tuple[tuple[Card, ...], ...]
    tableau: tuple[tuple[StackCard, ...], ...]
    stock: tuple[Card, ...]
    waste: tuple[Card, ...]
    variant: str = "klondike"
    draw_count: int = 1
    redeals_allowed: int | None = None
    redeals_used: int = 0

    @classmethod
    def empty(cls, *, variant: str = "klondike", draw_count: int = 1, redeals_allowed: int | None = None) -> GameState:
        """Return an empty state for constructing focused tests or fixtures."""
        return cls(
            foundations=empty_foundations(),
            tableau=empty_tableau(),
            stock=(),
            waste=(),
            variant=variant,
            draw_count=draw_count,
            redeals_allowed=redeals_allowed,
        )

    def foundation(self, suit: Suit) -> tuple[Card, ...]:
        """Return the foundation stack for ``suit``."""
        return self.foundations[SUIT_ORDER.index(suit)]

    @property
    def top_waste(self) -> Card | None:
        """Return the top waste card, if any."""
        if not self.waste:
            return None
        return self.waste[-1]

    def iter_known_cards(self) -> Iterator[Card]:
        """Yield every exact card identity present in the state."""
        for foundation in self.foundations:
            yield from foundation
        for column in self.tableau:
            for stack_card in column:
                yield stack_card.card
        yield from self.stock
        yield from self.waste

top_waste property

top_waste: Card | None

Return the top waste card, if any.

empty classmethod

empty(
    *,
    variant: str = "klondike",
    draw_count: int = 1,
    redeals_allowed: int | None = None,
) -> GameState

Return an empty state for constructing focused tests or fixtures.

Source code in src/patiencepilot/state.py
67
68
69
70
71
72
73
74
75
76
77
78
@classmethod
def empty(cls, *, variant: str = "klondike", draw_count: int = 1, redeals_allowed: int | None = None) -> GameState:
    """Return an empty state for constructing focused tests or fixtures."""
    return cls(
        foundations=empty_foundations(),
        tableau=empty_tableau(),
        stock=(),
        waste=(),
        variant=variant,
        draw_count=draw_count,
        redeals_allowed=redeals_allowed,
    )

foundation

foundation(suit: Suit) -> tuple[Card, ...]

Return the foundation stack for suit.

Source code in src/patiencepilot/state.py
80
81
82
def foundation(self, suit: Suit) -> tuple[Card, ...]:
    """Return the foundation stack for ``suit``."""
    return self.foundations[SUIT_ORDER.index(suit)]

iter_known_cards

iter_known_cards() -> Iterator[Card]

Yield every exact card identity present in the state.

Source code in src/patiencepilot/state.py
91
92
93
94
95
96
97
98
99
def iter_known_cards(self) -> Iterator[Card]:
    """Yield every exact card identity present in the state."""
    for foundation in self.foundations:
        yield from foundation
    for column in self.tableau:
        for stack_card in column:
            yield stack_card.card
    yield from self.stock
    yield from self.waste

StackCard dataclass

A card in a tableau stack with visibility metadata.

Source code in src/patiencepilot/state.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
@dataclass(frozen=True, slots=True)
class StackCard:
    """A card in a tableau stack with visibility metadata."""

    card: Card
    face_up: bool

    @classmethod
    def visible(cls, card: Card) -> StackCard:
        """Return a face-up tableau card."""
        return cls(card=card, face_up=True)

    @classmethod
    def hidden(cls, card: Card) -> StackCard:
        """Return a face-down tableau card."""
        return cls(card=card, face_up=False)

    @property
    def known_card(self) -> Card:
        """Return the exact card identity."""
        return self.card

    @property
    def visible_card(self) -> Card | None:
        """Return the card when it is both known and face up."""
        if self.face_up:
            return self.card
        return None

known_card property

known_card: Card

Return the exact card identity.

visible_card property

visible_card: Card | None

Return the card when it is both known and face up.

visible classmethod

visible(card: Card) -> StackCard

Return a face-up tableau card.

Source code in src/patiencepilot/state.py
21
22
23
24
@classmethod
def visible(cls, card: Card) -> StackCard:
    """Return a face-up tableau card."""
    return cls(card=card, face_up=True)

hidden classmethod

hidden(card: Card) -> StackCard

Return a face-down tableau card.

Source code in src/patiencepilot/state.py
26
27
28
29
@classmethod
def hidden(cls, card: Card) -> StackCard:
    """Return a face-down tableau card."""
    return cls(card=card, face_up=False)

KlondikeRules dataclass

Rules and options for Klondike Solitaire.

Source code in src/patiencepilot/variants/klondike.py
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
@dataclass(frozen=True, slots=True)
class KlondikeRules:
    """Rules and options for Klondike Solitaire."""

    draw_count: int = 1
    redeals: int | None = None

    name: ClassVar[str] = "klondike"

    def __post_init__(self) -> None:
        """Validate immutable rule options."""
        if self.draw_count < 1:
            msg = "draw_count must be at least 1"
            raise InvalidStateError(msg)
        if self.redeals is not None and self.redeals < 0:
            msg = "redeals must be non-negative or None"
            raise InvalidStateError(msg)

    def new_game(self, seed: Seed = None) -> GameState:
        """Return a new shuffled Klondike game state.

        Args:
            seed: Optional deterministic random seed.
        """
        deck = list(standard_deck())
        # Solitaire deals need deterministic game randomness for reproducible seeds.
        random.Random(seed).shuffle(deck)  # nosec B311
        return self.deal(deck)

    def deal(self, deck: Sequence[Card]) -> GameState:
        """Deal ``deck`` into a Klondike starting state.

        Args:
            deck: A complete 52-card deck. The end of the sequence is treated
                as the top of the deck.

        Raises:
            InvalidStateError: If ``deck`` is not a unique 52-card deck.
        """
        if len(deck) != len(standard_deck()) or len(set(deck)) != len(standard_deck()):
            msg = "Klondike deals require a unique 52-card deck"
            raise InvalidStateError(msg)

        cards = list(deck)
        tableau: list[tuple[StackCard, ...]] = []
        for column_index in range(N_TABLEAU_COLUMNS):
            column: list[StackCard] = []
            for row_index in range(column_index + 1):
                column.append(StackCard(card=cards.pop(), face_up=row_index == column_index))
            tableau.append(tuple(column))

        return GameState(
            foundations=tuple(() for _ in SUIT_ORDER),
            tableau=tuple(tableau),
            stock=tuple(cards),
            waste=(),
            variant=self.name,
            draw_count=self.draw_count,
            redeals_allowed=self.redeals,
        )

    def validate_state(self, state: GameState) -> None:
        """Validate that ``state`` is coherent for Klondike.

        Raises:
            InvalidStateError: If the state is malformed.
            UnsupportedVariantError: If the state belongs to another variant.
        """
        if state.variant != self.name:
            msg = f"expected variant {self.name!r}, got {state.variant!r}"
            raise UnsupportedVariantError(msg)
        if state.draw_count != self.draw_count:
            msg = f"state draw_count {state.draw_count} does not match rules draw_count {self.draw_count}"
            raise InvalidStateError(msg)
        if state.redeals_allowed != self.redeals:
            msg = f"state redeals_allowed {state.redeals_allowed!r} does not match rules redeals {self.redeals!r}"
            raise InvalidStateError(msg)
        if state.redeals_used < 0:
            msg = "redeals_used must be non-negative"
            raise InvalidStateError(msg)
        if self.redeals is not None and state.redeals_used > self.redeals:
            msg = "redeals_used cannot exceed redeals_allowed"
            raise InvalidStateError(msg)
        if len(state.foundations) != len(SUIT_ORDER):
            msg = "foundations must contain one stack per suit"
            raise InvalidStateError(msg)
        if len(state.tableau) != N_TABLEAU_COLUMNS:
            msg = f"Klondike tableau must contain {N_TABLEAU_COLUMNS} columns"
            raise InvalidStateError(msg)

        known_cards = tuple(state.iter_known_cards())
        if len(set(known_cards)) != len(known_cards):
            msg = "state contains duplicate known cards"
            raise InvalidStateError(msg)

        for suit in Suit:
            self._validate_foundation(suit, state.foundation(suit))

        for column_index, column in enumerate(state.tableau):
            for stack_card in column:
                if not isinstance(stack_card.card, Card):
                    msg = f"tableau column {column_index} contains a non-card value"
                    raise InvalidStateError(msg)

    def legal_moves(self, state: GameState) -> tuple[Move, ...]:
        """Return legal Klondike moves available from ``state``."""
        self.validate_state(state)
        moves: list[Move] = []

        if state.stock:
            moves.append(DrawFromStock())
        elif state.waste and self._can_recycle(state):
            moves.append(RecycleWaste())

        if state.waste:
            waste_card = state.waste[-1]
            if self._can_move_to_foundation(waste_card, state.foundation(waste_card.suit)):
                moves.append(WasteToFoundation())
            for destination in range(N_TABLEAU_COLUMNS):
                if self._can_place_on_tableau(waste_card, state.tableau[destination]):
                    moves.append(WasteToTableau(destination=destination))

        for source, column in enumerate(state.tableau):
            top_card = self._top_visible_card(column)
            if top_card is not None and self._can_move_to_foundation(top_card, state.foundation(top_card.suit)):
                moves.append(TableauToFoundation(source=source))

            for start_index in range(len(column)):
                moving_stack = column[start_index:]
                if not self._is_movable_tableau_stack(moving_stack):
                    continue
                moving_card = moving_stack[0].visible_card
                if moving_card is None:
                    continue
                count = len(moving_stack)
                for destination in range(N_TABLEAU_COLUMNS):
                    if source == destination:
                        continue
                    if self._can_place_on_tableau(moving_card, state.tableau[destination]):
                        moves.append(TableauToTableau(source=source, destination=destination, count=count))

        return tuple(moves)

    def apply_move(self, state: GameState, move: Move) -> MoveResult:
        """Apply a legal Klondike move and return the result.

        Raises:
            InvalidMoveError: If ``move`` is not legal from ``state``.
            InvalidStateError: If ``state`` is malformed.
        """
        self.validate_state(state)

        if isinstance(move, DrawFromStock):
            result = self._draw_from_stock(state, move)
        elif isinstance(move, RecycleWaste):
            result = self._recycle_waste(state, move)
        elif isinstance(move, WasteToFoundation):
            result = self._waste_to_foundation(state, move)
        elif isinstance(move, WasteToTableau):
            result = self._waste_to_tableau(state, move)
        elif isinstance(move, TableauToFoundation):
            result = self._tableau_to_foundation(state, move)
        elif isinstance(move, TableauToTableau):
            result = self._tableau_to_tableau(state, move)
        else:
            msg = f"unsupported Klondike move: {move!r}"
            raise InvalidMoveError(msg)

        self.validate_state(result.state)
        return result

    def is_won(self, state: GameState) -> bool:
        """Return whether all cards have been moved to the foundations."""
        self.validate_state(state)
        return all(len(state.foundation(suit)) == len(Rank) for suit in Suit)

    def _draw_from_stock(self, state: GameState, move: DrawFromStock) -> MoveResult:
        """Draw cards from stock to waste."""
        if not state.stock:
            msg = "cannot draw from an empty stock"
            raise InvalidMoveError(msg)

        stock = list(state.stock)
        waste = list(state.waste)
        drawn: list[Card] = []
        for _ in range(min(self.draw_count, len(stock))):
            card = stock.pop()
            waste.append(card)
            drawn.append(card)

        next_state = replace(state, stock=tuple(stock), waste=tuple(waste))
        return MoveResult(move=move, state=next_state, effects=(DrewStockCards(cards=tuple(drawn)),))

    def _recycle_waste(self, state: GameState, move: RecycleWaste) -> MoveResult:
        """Recycle waste into stock."""
        if state.stock:
            msg = "cannot recycle waste while stock is not empty"
            raise InvalidMoveError(msg)
        if not state.waste:
            msg = "cannot recycle an empty waste pile"
            raise InvalidMoveError(msg)
        if not self._can_recycle(state):
            msg = "redeal limit has been reached"
            raise InvalidMoveError(msg)

        next_state = replace(
            state,
            stock=tuple(reversed(state.waste)),
            waste=(),
            redeals_used=state.redeals_used + 1,
        )
        return MoveResult(move=move, state=next_state, effects=(RecycledWaste(count=len(state.waste)),))

    def _waste_to_foundation(self, state: GameState, move: WasteToFoundation) -> MoveResult:
        """Move waste top card to its foundation."""
        if not state.waste:
            msg = "cannot move from an empty waste pile"
            raise InvalidMoveError(msg)
        card = state.waste[-1]
        foundations = self._append_to_foundation(state, card)
        next_state = replace(state, foundations=foundations, waste=state.waste[:-1])
        return MoveResult(
            move=move,
            state=next_state,
            effects=(MovedCards(cards=(card,), source="waste", destination=f"foundation[{card.suit.code}]"),),
        )

    def _waste_to_tableau(self, state: GameState, move: WasteToTableau) -> MoveResult:
        """Move waste top card to a tableau column."""
        self._validate_column_index(move.destination)
        if not state.waste:
            msg = "cannot move from an empty waste pile"
            raise InvalidMoveError(msg)
        card = state.waste[-1]
        destination_column = state.tableau[move.destination]
        if not self._can_place_on_tableau(card, destination_column):
            msg = f"cannot move {card} to tableau column {move.destination}"
            raise InvalidMoveError(msg)

        tableau = self._replace_tableau_column(
            state.tableau,
            move.destination,
            (*destination_column, StackCard.visible(card)),
        )
        next_state = replace(state, tableau=tableau, waste=state.waste[:-1])
        return MoveResult(
            move=move,
            state=next_state,
            effects=(MovedCards(cards=(card,), source="waste", destination=f"tableau[{move.destination}]"),),
        )

    def _tableau_to_foundation(self, state: GameState, move: TableauToFoundation) -> MoveResult:
        """Move tableau top card to its foundation."""
        self._validate_column_index(move.source)
        source_column = state.tableau[move.source]
        card = self._top_visible_card(source_column)
        if card is None:
            msg = f"tableau column {move.source} has no visible top card"
            raise InvalidMoveError(msg)

        foundations = self._append_to_foundation(state, card)
        tableau = self._replace_tableau_column(state.tableau, move.source, source_column[:-1])
        tableau, reveal_effects = self._reveal_top_card(tableau, move.source)
        next_state = replace(state, foundations=foundations, tableau=tableau)
        return MoveResult(
            move=move,
            state=next_state,
            effects=(
                MovedCards(
                    cards=(card,),
                    source=f"tableau[{move.source}]",
                    destination=f"foundation[{card.suit.code}]",
                ),
                *reveal_effects,
            ),
        )

    def _tableau_to_tableau(self, state: GameState, move: TableauToTableau) -> MoveResult:
        """Move visible tableau cards between columns."""
        self._validate_column_index(move.source)
        self._validate_column_index(move.destination)
        if move.source == move.destination:
            msg = "source and destination tableau columns must differ"
            raise InvalidMoveError(msg)
        if move.count < 1:
            msg = "tableau move count must be at least 1"
            raise InvalidMoveError(msg)

        source_column = state.tableau[move.source]
        if move.count > len(source_column):
            msg = f"tableau column {move.source} does not contain {move.count} cards"
            raise InvalidMoveError(msg)

        moving_stack = source_column[-move.count :]
        if not self._is_movable_tableau_stack(moving_stack):
            msg = "tableau move must contain a face-up descending alternating-color stack"
            raise InvalidMoveError(msg)

        moving_card = moving_stack[0].visible_card
        if moving_card is None:
            msg = "tableau move starts with an unknown card"
            raise InvalidMoveError(msg)

        destination_column = state.tableau[move.destination]
        if not self._can_place_on_tableau(moving_card, destination_column):
            msg = f"cannot move {moving_card} to tableau column {move.destination}"
            raise InvalidMoveError(msg)

        tableau = self._replace_tableau_column(state.tableau, move.source, source_column[: -move.count])
        tableau = self._replace_tableau_column(tableau, move.destination, (*destination_column, *moving_stack))
        tableau, reveal_effects = self._reveal_top_card(tableau, move.source)
        moved_cards = tuple(stack_card.visible_card for stack_card in moving_stack)
        if any(card is None for card in moved_cards):
            msg = "tableau move contains an unknown card"
            raise InvalidMoveError(msg)
        cards = tuple(card for card in moved_cards if card is not None)
        next_state = replace(state, tableau=tableau)
        return MoveResult(
            move=move,
            state=next_state,
            effects=(
                MovedCards(
                    cards=cards,
                    source=f"tableau[{move.source}]",
                    destination=f"tableau[{move.destination}]",
                ),
                *reveal_effects,
            ),
        )

    def _append_to_foundation(self, state: GameState, card: Card) -> tuple[tuple[Card, ...], ...]:
        """Return foundations with ``card`` appended to its foundation."""
        foundation = state.foundation(card.suit)
        if not self._can_move_to_foundation(card, foundation):
            msg = f"cannot move {card} to foundation"
            raise InvalidMoveError(msg)

        foundations = list(state.foundations)
        foundations[SUIT_ORDER.index(card.suit)] = (*foundation, card)
        return tuple(foundations)

    def _reveal_top_card(
        self,
        tableau: tuple[tuple[StackCard, ...], ...],
        column_index: int,
    ) -> tuple[tuple[tuple[StackCard, ...], ...], tuple[MoveEffect, ...]]:
        """Reveal the top card in a tableau column when possible."""
        column = tableau[column_index]
        if not column or column[-1].face_up:
            return tableau, ()

        revealed_column = (*column[:-1], StackCard.visible(column[-1].card))
        return (
            self._replace_tableau_column(tableau, column_index, revealed_column),
            (RevealedTableauCard(column=column_index, card=column[-1].card),),
        )

    @staticmethod
    def _replace_tableau_column(
        tableau: tuple[tuple[StackCard, ...], ...],
        column_index: int,
        column: tuple[StackCard, ...],
    ) -> tuple[tuple[StackCard, ...], ...]:
        """Return tableau with one column replaced."""
        next_tableau = list(tableau)
        next_tableau[column_index] = column
        return tuple(next_tableau)

    @staticmethod
    def _validate_column_index(column_index: int) -> None:
        """Validate a tableau column index."""
        if column_index < 0 or column_index >= N_TABLEAU_COLUMNS:
            msg = f"tableau column index out of range: {column_index}"
            raise InvalidMoveError(msg)

    @staticmethod
    def _validate_foundation(suit: Suit, foundation: tuple[Card, ...]) -> None:
        """Validate one foundation stack."""
        for expected_rank, card in enumerate(foundation, start=Rank.ACE.value):
            if card.suit != suit or card.rank.value != expected_rank:
                msg = f"foundation {suit.code} is not ordered from ace upward"
                raise InvalidStateError(msg)

    @staticmethod
    def _top_visible_card(column: tuple[StackCard, ...]) -> Card | None:
        """Return the visible top card for a tableau column."""
        if not column:
            return None
        return column[-1].visible_card

    @staticmethod
    def _can_move_to_foundation(card: Card, foundation: tuple[Card, ...]) -> bool:
        """Return whether ``card`` can move to ``foundation``."""
        if not foundation:
            return card.rank == Rank.ACE
        top_card = foundation[-1]
        return card.suit == top_card.suit and card.rank.value == top_card.rank.value + 1

    @staticmethod
    def _can_place_on_tableau(card: Card, destination: tuple[StackCard, ...]) -> bool:
        """Return whether ``card`` can be placed on a tableau destination."""
        if not destination:
            return card.rank == Rank.KING
        top_card = destination[-1].visible_card
        if top_card is None:
            return False
        return card.color != top_card.color and card.rank.value == top_card.rank.value - 1

    @staticmethod
    def _is_movable_tableau_stack(stack: tuple[StackCard, ...]) -> bool:
        """Return whether ``stack`` is a movable face-up Klondike sequence."""
        if not stack:
            return False

        visible_cards = tuple(stack_card.visible_card for stack_card in stack)
        if any(card is None for card in visible_cards):
            return False

        cards = tuple(card for card in visible_cards if card is not None)
        return all(
            lower.color != upper.color and upper.rank.value == lower.rank.value - 1 for lower, upper in pairwise(cards)
        )

    def _can_recycle(self, state: GameState) -> bool:
        """Return whether waste can be recycled into stock."""
        return self.redeals is None or state.redeals_used < self.redeals

__post_init__

__post_init__() -> None

Validate immutable rule options.

Source code in src/patiencepilot/variants/klondike.py
41
42
43
44
45
46
47
48
def __post_init__(self) -> None:
    """Validate immutable rule options."""
    if self.draw_count < 1:
        msg = "draw_count must be at least 1"
        raise InvalidStateError(msg)
    if self.redeals is not None and self.redeals < 0:
        msg = "redeals must be non-negative or None"
        raise InvalidStateError(msg)

new_game

new_game(seed: Seed = None) -> GameState

Return a new shuffled Klondike game state.

Parameters:

Name Type Description Default
seed Seed

Optional deterministic random seed.

None
Source code in src/patiencepilot/variants/klondike.py
50
51
52
53
54
55
56
57
58
59
def new_game(self, seed: Seed = None) -> GameState:
    """Return a new shuffled Klondike game state.

    Args:
        seed: Optional deterministic random seed.
    """
    deck = list(standard_deck())
    # Solitaire deals need deterministic game randomness for reproducible seeds.
    random.Random(seed).shuffle(deck)  # nosec B311
    return self.deal(deck)

deal

deal(deck: Sequence[Card]) -> GameState

Deal deck into a Klondike starting state.

Parameters:

Name Type Description Default
deck Sequence[Card]

A complete 52-card deck. The end of the sequence is treated as the top of the deck.

required

Raises:

Type Description
InvalidStateError

If deck is not a unique 52-card deck.

Source code in src/patiencepilot/variants/klondike.py
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
def deal(self, deck: Sequence[Card]) -> GameState:
    """Deal ``deck`` into a Klondike starting state.

    Args:
        deck: A complete 52-card deck. The end of the sequence is treated
            as the top of the deck.

    Raises:
        InvalidStateError: If ``deck`` is not a unique 52-card deck.
    """
    if len(deck) != len(standard_deck()) or len(set(deck)) != len(standard_deck()):
        msg = "Klondike deals require a unique 52-card deck"
        raise InvalidStateError(msg)

    cards = list(deck)
    tableau: list[tuple[StackCard, ...]] = []
    for column_index in range(N_TABLEAU_COLUMNS):
        column: list[StackCard] = []
        for row_index in range(column_index + 1):
            column.append(StackCard(card=cards.pop(), face_up=row_index == column_index))
        tableau.append(tuple(column))

    return GameState(
        foundations=tuple(() for _ in SUIT_ORDER),
        tableau=tuple(tableau),
        stock=tuple(cards),
        waste=(),
        variant=self.name,
        draw_count=self.draw_count,
        redeals_allowed=self.redeals,
    )

validate_state

validate_state(state: GameState) -> None

Validate that state is coherent for Klondike.

Raises:

Type Description
InvalidStateError

If the state is malformed.

UnsupportedVariantError

If the state belongs to another variant.

Source code in src/patiencepilot/variants/klondike.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
def validate_state(self, state: GameState) -> None:
    """Validate that ``state`` is coherent for Klondike.

    Raises:
        InvalidStateError: If the state is malformed.
        UnsupportedVariantError: If the state belongs to another variant.
    """
    if state.variant != self.name:
        msg = f"expected variant {self.name!r}, got {state.variant!r}"
        raise UnsupportedVariantError(msg)
    if state.draw_count != self.draw_count:
        msg = f"state draw_count {state.draw_count} does not match rules draw_count {self.draw_count}"
        raise InvalidStateError(msg)
    if state.redeals_allowed != self.redeals:
        msg = f"state redeals_allowed {state.redeals_allowed!r} does not match rules redeals {self.redeals!r}"
        raise InvalidStateError(msg)
    if state.redeals_used < 0:
        msg = "redeals_used must be non-negative"
        raise InvalidStateError(msg)
    if self.redeals is not None and state.redeals_used > self.redeals:
        msg = "redeals_used cannot exceed redeals_allowed"
        raise InvalidStateError(msg)
    if len(state.foundations) != len(SUIT_ORDER):
        msg = "foundations must contain one stack per suit"
        raise InvalidStateError(msg)
    if len(state.tableau) != N_TABLEAU_COLUMNS:
        msg = f"Klondike tableau must contain {N_TABLEAU_COLUMNS} columns"
        raise InvalidStateError(msg)

    known_cards = tuple(state.iter_known_cards())
    if len(set(known_cards)) != len(known_cards):
        msg = "state contains duplicate known cards"
        raise InvalidStateError(msg)

    for suit in Suit:
        self._validate_foundation(suit, state.foundation(suit))

    for column_index, column in enumerate(state.tableau):
        for stack_card in column:
            if not isinstance(stack_card.card, Card):
                msg = f"tableau column {column_index} contains a non-card value"
                raise InvalidStateError(msg)

legal_moves

legal_moves(state: GameState) -> tuple[Move, ...]

Return legal Klondike moves available from state.

Source code in src/patiencepilot/variants/klondike.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
def legal_moves(self, state: GameState) -> tuple[Move, ...]:
    """Return legal Klondike moves available from ``state``."""
    self.validate_state(state)
    moves: list[Move] = []

    if state.stock:
        moves.append(DrawFromStock())
    elif state.waste and self._can_recycle(state):
        moves.append(RecycleWaste())

    if state.waste:
        waste_card = state.waste[-1]
        if self._can_move_to_foundation(waste_card, state.foundation(waste_card.suit)):
            moves.append(WasteToFoundation())
        for destination in range(N_TABLEAU_COLUMNS):
            if self._can_place_on_tableau(waste_card, state.tableau[destination]):
                moves.append(WasteToTableau(destination=destination))

    for source, column in enumerate(state.tableau):
        top_card = self._top_visible_card(column)
        if top_card is not None and self._can_move_to_foundation(top_card, state.foundation(top_card.suit)):
            moves.append(TableauToFoundation(source=source))

        for start_index in range(len(column)):
            moving_stack = column[start_index:]
            if not self._is_movable_tableau_stack(moving_stack):
                continue
            moving_card = moving_stack[0].visible_card
            if moving_card is None:
                continue
            count = len(moving_stack)
            for destination in range(N_TABLEAU_COLUMNS):
                if source == destination:
                    continue
                if self._can_place_on_tableau(moving_card, state.tableau[destination]):
                    moves.append(TableauToTableau(source=source, destination=destination, count=count))

    return tuple(moves)

apply_move

apply_move(state: GameState, move: Move) -> MoveResult

Apply a legal Klondike move and return the result.

Raises:

Type Description
InvalidMoveError

If move is not legal from state.

InvalidStateError

If state is malformed.

Source code in src/patiencepilot/variants/klondike.py
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
def apply_move(self, state: GameState, move: Move) -> MoveResult:
    """Apply a legal Klondike move and return the result.

    Raises:
        InvalidMoveError: If ``move`` is not legal from ``state``.
        InvalidStateError: If ``state`` is malformed.
    """
    self.validate_state(state)

    if isinstance(move, DrawFromStock):
        result = self._draw_from_stock(state, move)
    elif isinstance(move, RecycleWaste):
        result = self._recycle_waste(state, move)
    elif isinstance(move, WasteToFoundation):
        result = self._waste_to_foundation(state, move)
    elif isinstance(move, WasteToTableau):
        result = self._waste_to_tableau(state, move)
    elif isinstance(move, TableauToFoundation):
        result = self._tableau_to_foundation(state, move)
    elif isinstance(move, TableauToTableau):
        result = self._tableau_to_tableau(state, move)
    else:
        msg = f"unsupported Klondike move: {move!r}"
        raise InvalidMoveError(msg)

    self.validate_state(result.state)
    return result

is_won

is_won(state: GameState) -> bool

Return whether all cards have been moved to the foundations.

Source code in src/patiencepilot/variants/klondike.py
203
204
205
206
def is_won(self, state: GameState) -> bool:
    """Return whether all cards have been moved to the foundations."""
    self.validate_state(state)
    return all(len(state.foundation(suit)) == len(Rank) for suit in Suit)

Variant

Bases: Protocol

Protocol implemented by Solitaire rule sets.

Source code in src/patiencepilot/variants/base.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Variant(Protocol):
    """Protocol implemented by Solitaire rule sets."""

    name: ClassVar[str]

    def new_game(self, seed: Seed = None) -> GameState:
        """Return a new game state."""
        ...

    def validate_state(self, state: GameState) -> None:
        """Validate that ``state`` is coherent for this variant."""
        ...

    def legal_moves(self, state: GameState) -> tuple[Move, ...]:
        """Return legal moves available from ``state``."""
        ...

    def apply_move(self, state: GameState, move: Move) -> MoveResult:
        """Apply ``move`` and return the resulting state and effects."""
        ...

    def is_won(self, state: GameState) -> bool:
        """Return whether ``state`` is a winning state."""
        ...

new_game

new_game(seed: Seed = None) -> GameState

Return a new game state.

Source code in src/patiencepilot/variants/base.py
18
19
20
def new_game(self, seed: Seed = None) -> GameState:
    """Return a new game state."""
    ...

validate_state

validate_state(state: GameState) -> None

Validate that state is coherent for this variant.

Source code in src/patiencepilot/variants/base.py
22
23
24
def validate_state(self, state: GameState) -> None:
    """Validate that ``state`` is coherent for this variant."""
    ...

legal_moves

legal_moves(state: GameState) -> tuple[Move, ...]

Return legal moves available from state.

Source code in src/patiencepilot/variants/base.py
26
27
28
def legal_moves(self, state: GameState) -> tuple[Move, ...]:
    """Return legal moves available from ``state``."""
    ...

apply_move

apply_move(state: GameState, move: Move) -> MoveResult

Apply move and return the resulting state and effects.

Source code in src/patiencepilot/variants/base.py
30
31
32
def apply_move(self, state: GameState, move: Move) -> MoveResult:
    """Apply ``move`` and return the resulting state and effects."""
    ...

is_won

is_won(state: GameState) -> bool

Return whether state is a winning state.

Source code in src/patiencepilot/variants/base.py
34
35
36
def is_won(self, state: GameState) -> bool:
    """Return whether ``state`` is a winning state."""
    ...

VariantDefinition dataclass

Registered Solitaire variant plus its option conversion functions.

Source code in src/patiencepilot/variants/registry.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
@dataclass(frozen=True, slots=True)
class VariantDefinition:
    """Registered Solitaire variant plus its option conversion functions."""

    name: str
    factory: VariantFactory
    state_options: StateOptionsResolver
    aliases: tuple[str, ...] = ()

    def resolve(self, options: VariantOptions | None = None) -> Variant:
        """Return a rules object for this variant.

        Args:
            options: Variant-specific configuration values.
        """
        return self.factory({} if options is None else options)

resolve

resolve(options: VariantOptions | None = None) -> Variant

Return a rules object for this variant.

Parameters:

Name Type Description Default
options VariantOptions | None

Variant-specific configuration values.

None
Source code in src/patiencepilot/variants/registry.py
42
43
44
45
46
47
48
def resolve(self, options: VariantOptions | None = None) -> Variant:
    """Return a rules object for this variant.

    Args:
        options: Variant-specific configuration values.
    """
    return self.factory({} if options is None else options)

VariantRegistry dataclass

Small immutable registry of supported Solitaire variants.

Source code in src/patiencepilot/variants/registry.py
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
@dataclass(frozen=True, slots=True)
class VariantRegistry:
    """Small immutable registry of supported Solitaire variants."""

    definitions: tuple[VariantDefinition, ...]

    def __post_init__(self) -> None:
        """Validate registry keys."""
        keys: set[str] = set()
        for definition in self.definitions:
            for name in (definition.name, *definition.aliases):
                normalized = _normalize_variant_name(name)
                if normalized in keys:
                    msg = f"duplicate variant registry name: {name!r}"
                    raise InvalidStateError(msg)
                keys.add(normalized)

    @property
    def names(self) -> tuple[str, ...]:
        """Return canonical registered variant names."""
        return tuple(definition.name for definition in self.definitions)

    def register(self, definition: VariantDefinition) -> VariantRegistry:
        """Return a new registry that also contains ``definition``.

        Args:
            definition: Variant definition to add.
        """
        return VariantRegistry((*self.definitions, definition))

    def definition_for(self, name: str) -> VariantDefinition:
        """Return the registered definition for ``name`` or alias.

        Args:
            name: Variant name or alias.

        Raises:
            UnsupportedVariantError: If no variant is registered for ``name``.
        """
        normalized = _normalize_variant_name(name)
        for definition in self.definitions:
            if normalized == _normalize_variant_name(definition.name):
                return definition
            if any(normalized == _normalize_variant_name(alias) for alias in definition.aliases):
                return definition

        msg = f"unsupported variant: {name!r}"
        raise UnsupportedVariantError(msg)

    def resolve(self, name: str, options: VariantOptions | None = None) -> Variant:
        """Return a rules object by variant name and options.

        Args:
            name: Variant name or alias.
            options: Variant-specific configuration values.
        """
        return self.definition_for(name).resolve(options)

    def options_from_state(self, state: GameState) -> dict[str, object]:
        """Return registry options that reproduce ``state`` rules.

        Args:
            state: State whose variant metadata should be converted.
        """
        return self.definition_for(state.variant).state_options(state)

    def resolve_state(self, state: GameState) -> Variant:
        """Return rules for the variant metadata stored in ``state``.

        Args:
            state: State containing variant name and option metadata.
        """
        return self.resolve(state.variant, self.options_from_state(state))

names property

names: tuple[str, ...]

Return canonical registered variant names.

__post_init__

__post_init__() -> None

Validate registry keys.

Source code in src/patiencepilot/variants/registry.py
57
58
59
60
61
62
63
64
65
66
def __post_init__(self) -> None:
    """Validate registry keys."""
    keys: set[str] = set()
    for definition in self.definitions:
        for name in (definition.name, *definition.aliases):
            normalized = _normalize_variant_name(name)
            if normalized in keys:
                msg = f"duplicate variant registry name: {name!r}"
                raise InvalidStateError(msg)
            keys.add(normalized)

register

register(definition: VariantDefinition) -> VariantRegistry

Return a new registry that also contains definition.

Parameters:

Name Type Description Default
definition VariantDefinition

Variant definition to add.

required
Source code in src/patiencepilot/variants/registry.py
73
74
75
76
77
78
79
def register(self, definition: VariantDefinition) -> VariantRegistry:
    """Return a new registry that also contains ``definition``.

    Args:
        definition: Variant definition to add.
    """
    return VariantRegistry((*self.definitions, definition))

definition_for

definition_for(name: str) -> VariantDefinition

Return the registered definition for name or alias.

Parameters:

Name Type Description Default
name str

Variant name or alias.

required

Raises:

Type Description
UnsupportedVariantError

If no variant is registered for name.

Source code in src/patiencepilot/variants/registry.py
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
def definition_for(self, name: str) -> VariantDefinition:
    """Return the registered definition for ``name`` or alias.

    Args:
        name: Variant name or alias.

    Raises:
        UnsupportedVariantError: If no variant is registered for ``name``.
    """
    normalized = _normalize_variant_name(name)
    for definition in self.definitions:
        if normalized == _normalize_variant_name(definition.name):
            return definition
        if any(normalized == _normalize_variant_name(alias) for alias in definition.aliases):
            return definition

    msg = f"unsupported variant: {name!r}"
    raise UnsupportedVariantError(msg)

resolve

resolve(
    name: str, options: VariantOptions | None = None
) -> Variant

Return a rules object by variant name and options.

Parameters:

Name Type Description Default
name str

Variant name or alias.

required
options VariantOptions | None

Variant-specific configuration values.

None
Source code in src/patiencepilot/variants/registry.py
100
101
102
103
104
105
106
107
def resolve(self, name: str, options: VariantOptions | None = None) -> Variant:
    """Return a rules object by variant name and options.

    Args:
        name: Variant name or alias.
        options: Variant-specific configuration values.
    """
    return self.definition_for(name).resolve(options)

options_from_state

options_from_state(state: GameState) -> dict[str, object]

Return registry options that reproduce state rules.

Parameters:

Name Type Description Default
state GameState

State whose variant metadata should be converted.

required
Source code in src/patiencepilot/variants/registry.py
109
110
111
112
113
114
115
def options_from_state(self, state: GameState) -> dict[str, object]:
    """Return registry options that reproduce ``state`` rules.

    Args:
        state: State whose variant metadata should be converted.
    """
    return self.definition_for(state.variant).state_options(state)

resolve_state

resolve_state(state: GameState) -> Variant

Return rules for the variant metadata stored in state.

Parameters:

Name Type Description Default
state GameState

State containing variant name and option metadata.

required
Source code in src/patiencepilot/variants/registry.py
117
118
119
120
121
122
123
def resolve_state(self, state: GameState) -> Variant:
    """Return rules for the variant metadata stored in ``state``.

    Args:
        state: State containing variant name and option metadata.
    """
    return self.resolve(state.variant, self.options_from_state(state))

PlayerStackCard dataclass

A tableau card as known to a player.

Source code in src/patiencepilot/view.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
@dataclass(frozen=True, slots=True)
class PlayerStackCard:
    """A tableau card as known to a player."""

    card: Card | None
    face_up: bool

    def __post_init__(self) -> None:
        """Validate player-view visibility invariants."""
        if self.face_up and self.card is None:
            msg = "face-up player-view cards must expose a card"
            raise InvalidStateError(msg)
        if not self.face_up and self.card is not None:
            msg = "face-down player-view cards must not expose a card"
            raise InvalidStateError(msg)

    @classmethod
    def visible(cls, card: Card) -> PlayerStackCard:
        """Return a face-up player-visible tableau card."""
        return cls(card=card, face_up=True)

    @classmethod
    def hidden(cls) -> PlayerStackCard:
        """Return a face-down player-hidden tableau card."""
        return cls(card=None, face_up=False)

    @property
    def visible_card(self) -> Card | None:
        """Return the card if it is visible to the player."""
        return self.card if self.face_up else None

visible_card property

visible_card: Card | None

Return the card if it is visible to the player.

__post_init__

__post_init__() -> None

Validate player-view visibility invariants.

Source code in src/patiencepilot/view.py
20
21
22
23
24
25
26
27
def __post_init__(self) -> None:
    """Validate player-view visibility invariants."""
    if self.face_up and self.card is None:
        msg = "face-up player-view cards must expose a card"
        raise InvalidStateError(msg)
    if not self.face_up and self.card is not None:
        msg = "face-down player-view cards must not expose a card"
        raise InvalidStateError(msg)

visible classmethod

visible(card: Card) -> PlayerStackCard

Return a face-up player-visible tableau card.

Source code in src/patiencepilot/view.py
29
30
31
32
@classmethod
def visible(cls, card: Card) -> PlayerStackCard:
    """Return a face-up player-visible tableau card."""
    return cls(card=card, face_up=True)

hidden classmethod

hidden() -> PlayerStackCard

Return a face-down player-hidden tableau card.

Source code in src/patiencepilot/view.py
34
35
36
37
@classmethod
def hidden(cls) -> PlayerStackCard:
    """Return a face-down player-hidden tableau card."""
    return cls(card=None, face_up=False)

PlayerView dataclass

A state projection containing only what a perfect human player may know.

Source code in src/patiencepilot/view.py
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
@dataclass(frozen=True, slots=True)
class PlayerView:
    """A state projection containing only what a perfect human player may know."""

    foundations: tuple[tuple[Card, ...], ...]
    tableau: tuple[tuple[PlayerStackCard, ...], ...]
    waste: tuple[Card, ...]
    seen_cards: tuple[Card, ...]
    unknown: UnknownCardConstraints
    variant: str = "klondike"
    draw_count: int = 1
    redeals_allowed: int | None = None
    redeals_used: int = 0

    @classmethod
    def from_state(cls, state: GameState, *, seen_cards: Iterable[Card] = ()) -> PlayerView:
        """Project an authoritative game state into a player-known view.

        Args:
            state: Authoritative state to project.
            seen_cards: Cards observed earlier in the game, even if they are no
                longer visible.
        """
        tableau = tuple(
            tuple(
                PlayerStackCard.visible(stack_card.card) if stack_card.face_up else PlayerStackCard.hidden()
                for stack_card in column
            )
            for column in state.tableau
        )
        visible_cards = tuple(cls._iter_visible_cards(state))
        known_cards = _standard_deck_ordered_unique((*seen_cards, *visible_cards))
        known_set = set(known_cards)
        unknown = UnknownCardConstraints(
            hidden_tableau_counts=tuple(
                sum(1 for stack_card in column if not stack_card.face_up) for column in state.tableau
            ),
            stock_count=len(state.stock),
            unseen_cards=tuple(card for card in standard_deck() if card not in known_set),
        )
        return cls(
            foundations=state.foundations,
            tableau=tableau,
            waste=state.waste,
            seen_cards=known_cards,
            unknown=unknown,
            variant=state.variant,
            draw_count=state.draw_count,
            redeals_allowed=state.redeals_allowed,
            redeals_used=state.redeals_used,
        )

    def foundation(self, suit: Suit) -> tuple[Card, ...]:
        """Return the visible foundation stack for ``suit``."""
        return self.foundations[SUIT_ORDER.index(suit)]

    @property
    def stock_count(self) -> int:
        """Return the number of cards hidden in stock."""
        return self.unknown.stock_count

    def iter_visible_cards(self) -> Iterator[Card]:
        """Yield cards currently visible to the player."""
        yield from self._iter_visible_cards(self)

    @staticmethod
    def _iter_visible_cards(state: GameState | PlayerView) -> Iterator[Card]:
        """Yield visible cards from an authoritative state or player view."""
        for foundation in state.foundations:
            yield from foundation
        for column in state.tableau:
            for stack_card in column:
                if stack_card.visible_card is not None:
                    yield stack_card.visible_card
        yield from state.waste

stock_count property

stock_count: int

Return the number of cards hidden in stock.

from_state classmethod

from_state(
    state: GameState, *, seen_cards: Iterable[Card] = ()
) -> PlayerView

Project an authoritative game state into a player-known view.

Parameters:

Name Type Description Default
state GameState

Authoritative state to project.

required
seen_cards Iterable[Card]

Cards observed earlier in the game, even if they are no longer visible.

()
Source code in src/patiencepilot/view.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
@classmethod
def from_state(cls, state: GameState, *, seen_cards: Iterable[Card] = ()) -> PlayerView:
    """Project an authoritative game state into a player-known view.

    Args:
        state: Authoritative state to project.
        seen_cards: Cards observed earlier in the game, even if they are no
            longer visible.
    """
    tableau = tuple(
        tuple(
            PlayerStackCard.visible(stack_card.card) if stack_card.face_up else PlayerStackCard.hidden()
            for stack_card in column
        )
        for column in state.tableau
    )
    visible_cards = tuple(cls._iter_visible_cards(state))
    known_cards = _standard_deck_ordered_unique((*seen_cards, *visible_cards))
    known_set = set(known_cards)
    unknown = UnknownCardConstraints(
        hidden_tableau_counts=tuple(
            sum(1 for stack_card in column if not stack_card.face_up) for column in state.tableau
        ),
        stock_count=len(state.stock),
        unseen_cards=tuple(card for card in standard_deck() if card not in known_set),
    )
    return cls(
        foundations=state.foundations,
        tableau=tableau,
        waste=state.waste,
        seen_cards=known_cards,
        unknown=unknown,
        variant=state.variant,
        draw_count=state.draw_count,
        redeals_allowed=state.redeals_allowed,
        redeals_used=state.redeals_used,
    )

foundation

foundation(suit: Suit) -> tuple[Card, ...]

Return the visible foundation stack for suit.

Source code in src/patiencepilot/view.py
128
129
130
def foundation(self, suit: Suit) -> tuple[Card, ...]:
    """Return the visible foundation stack for ``suit``."""
    return self.foundations[SUIT_ORDER.index(suit)]

iter_visible_cards

iter_visible_cards() -> Iterator[Card]

Yield cards currently visible to the player.

Source code in src/patiencepilot/view.py
137
138
139
def iter_visible_cards(self) -> Iterator[Card]:
    """Yield cards currently visible to the player."""
    yield from self._iter_visible_cards(self)

UnknownCardConstraints dataclass

Constraints for cards not currently identified in the player view.

Source code in src/patiencepilot/view.py
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
@dataclass(frozen=True, slots=True)
class UnknownCardConstraints:
    """Constraints for cards not currently identified in the player view."""

    hidden_tableau_counts: tuple[int, ...]
    stock_count: int
    unseen_cards: tuple[Card, ...]

    def __post_init__(self) -> None:
        """Validate unknown-card constraint counts."""
        if len(self.hidden_tableau_counts) != N_TABLEAU_COLUMNS:
            msg = f"hidden_tableau_counts must contain {N_TABLEAU_COLUMNS} entries"
            raise InvalidStateError(msg)
        if any(count < 0 for count in self.hidden_tableau_counts):
            msg = "hidden tableau counts must be non-negative"
            raise InvalidStateError(msg)
        if self.stock_count < 0:
            msg = "stock_count must be non-negative"
            raise InvalidStateError(msg)

    @property
    def hidden_tableau_count(self) -> int:
        """Return the total number of face-down tableau cards."""
        return sum(self.hidden_tableau_counts)

    @property
    def hidden_position_count(self) -> int:
        """Return the number of hidden positions in stock and tableau."""
        return self.stock_count + self.hidden_tableau_count

hidden_tableau_count property

hidden_tableau_count: int

Return the total number of face-down tableau cards.

hidden_position_count property

hidden_position_count: int

Return the number of hidden positions in stock and tableau.

__post_init__

__post_init__() -> None

Validate unknown-card constraint counts.

Source code in src/patiencepilot/view.py
53
54
55
56
57
58
59
60
61
62
63
def __post_init__(self) -> None:
    """Validate unknown-card constraint counts."""
    if len(self.hidden_tableau_counts) != N_TABLEAU_COLUMNS:
        msg = f"hidden_tableau_counts must contain {N_TABLEAU_COLUMNS} entries"
        raise InvalidStateError(msg)
    if any(count < 0 for count in self.hidden_tableau_counts):
        msg = "hidden tableau counts must be non-negative"
        raise InvalidStateError(msg)
    if self.stock_count < 0:
        msg = "stock_count must be non-negative"
        raise InvalidStateError(msg)

export_session

export_session(
    session: GameSession,
    *,
    seen_cards: Iterable[Card] | None = None,
) -> SerializedSession

Return a JSON-compatible session payload.

Parameters:

Name Type Description Default
session GameSession

Session to export.

required
seen_cards Iterable[Card] | None

Cards known to the player from earlier observation history. When omitted, session.metadata["seen_cards"] is used if present.

None
Source code in src/patiencepilot/app.py
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
def export_session(session: GameSession, *, seen_cards: Iterable[Card] | None = None) -> SerializedSession:
    """Return a JSON-compatible session payload.

    Args:
        session: Session to export.
        seen_cards: Cards known to the player from earlier observation history.
            When omitted, ``session.metadata["seen_cards"]`` is used if present.
    """
    initial_state = session.history[0].before if session.history else session.state
    known_seen_cards = _seen_cards_for_session(session, seen_cards)
    player_view = PlayerView.from_state(session.state, seen_cards=known_seen_cards)
    return {
        "schema_version": SCHEMA_VERSION,
        "variant": session.state.variant,
        "options": variant_options_from_state(session.state),
        "seed": session.seed,
        "initial_state": serialize_state(initial_state),
        "current_state": serialize_state(session.state),
        "state_notation": state_to_text(session.state),
        "history": [serialize_move(move) for move in session.move_history],
        "redo": [serialize_move(step.move) for step in session.redo_history],
        "seen_cards": [card.code for card in known_seen_cards],
        "player_view": serialize_player_view(player_view),
        "metadata": dict(session.metadata),
        "ui_state": dict(session.ui_state),
    }

import_session

import_session(data: Mapping[str, object]) -> GameSession

Return a session from a serialized payload.

Parameters:

Name Type Description Default
data Mapping[str, object]

Session payload created by :func:export_session.

required

Raises:

Type Description
NotationError

If the payload cannot be imported.

Source code in src/patiencepilot/app.py
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
def import_session(data: Mapping[str, object]) -> GameSession:
    """Return a session from a serialized payload.

    Args:
        data: Session payload created by :func:`export_session`.

    Raises:
        NotationError: If the payload cannot be imported.
    """
    migrated = migrate_session_payload(data)
    variant = _str_value(migrated, "variant")
    options = _dict_value(migrated, "options")
    initial_state = deserialize_state(_mapping_value(migrated, "initial_state"))
    current_state = deserialize_state(_mapping_value(migrated, "current_state"))
    state_notation = migrated.get("state_notation")
    if isinstance(state_notation, str) and state_from_text(state_notation) != current_state:
        msg = "state_notation does not match current_state"
        raise NotationError(msg)

    history = _deserialize_move_list(migrated, "history")
    redo = _deserialize_move_list(migrated, "redo")
    metadata = _dict_value(migrated, "metadata")
    ui_state = _dict_value(migrated, "ui_state")
    seen_cards = _cards_from_codes(_list_value(migrated, "seen_cards"), "seen_cards")
    if seen_cards and "seen_cards" not in metadata:
        metadata["seen_cards"] = [card.code for card in seen_cards]

    resolve_variant(variant, options).validate_state(initial_state)
    session = GameSession(
        state=initial_state,
        variant=variant,
        seed=_seed_value(migrated.get("seed")),
        metadata=metadata,
        ui_state=ui_state,
    )
    for move in history:
        session.apply_move(move)

    if session.state != current_state:
        msg = "session history does not reproduce current_state"
        raise NotationError(msg)

    for move in redo:
        session.apply_move(move)
    for _ in redo:
        session.undo()

    return session

migrate_session_payload

migrate_session_payload(
    data: Mapping[str, object],
) -> dict[str, object]

Return a best-effort alpha migration to session schema version 1.

Source code in src/patiencepilot/app.py
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
def migrate_session_payload(data: Mapping[str, object]) -> dict[str, object]:
    """Return a best-effort alpha migration to session schema version 1."""
    migrated = dict(data)
    schema_version = migrated.get("schema_version", SCHEMA_VERSION)
    if schema_version != SCHEMA_VERSION:
        msg = f"unsupported session schema_version: {schema_version!r}"
        raise NotationError(msg)

    if "current_state" not in migrated and "state" in migrated:
        migrated["current_state"] = migrated["state"]
    if "initial_state" not in migrated and "current_state" in migrated:
        migrated["initial_state"] = migrated["current_state"]

    current_state = migrated.get("current_state")
    if isinstance(current_state, Mapping):
        migrated.setdefault("variant", current_state.get("variant", "klondike"))
        migrated.setdefault("options", current_state.get("options", {}))
    else:
        migrated.setdefault("variant", "klondike")
        migrated.setdefault("options", {})

    migrated["schema_version"] = SCHEMA_VERSION
    migrated.setdefault("seed", None)
    migrated.setdefault("history", [])
    migrated.setdefault("redo", [])
    migrated.setdefault("metadata", {})
    migrated.setdefault("ui_state", {})
    migrated.setdefault("seen_cards", [])
    return migrated

validate_session_payload

validate_session_payload(
    data: Mapping[str, object],
) -> ValidationReport

Validate a serialized session payload without raising.

Source code in src/patiencepilot/app.py
298
299
300
301
302
303
304
def validate_session_payload(data: Mapping[str, object]) -> ValidationReport:
    """Validate a serialized session payload without raising."""
    try:
        import_session(data)
    except PatiencePilotError as error:
        return _validation_report("session", error)
    return ValidationReport(ok=True)

validate_state_payload

validate_state_payload(
    data: Mapping[str, object],
) -> ValidationReport

Validate a serialized state payload without raising.

Source code in src/patiencepilot/app.py
307
308
309
310
311
312
313
314
315
316
317
318
def validate_state_payload(data: Mapping[str, object]) -> ValidationReport:
    """Validate a serialized state payload without raising."""
    result = validate_serialized_state(data)
    if result.ok:
        return ValidationReport(ok=True)
    diagnostic = result.diagnostics[0]
    return ValidationReport(
        ok=False,
        message=diagnostic.message,
        error_type=diagnostic.error_type,
        diagnostics=result.diagnostics,
    )

standard_deck

standard_deck() -> tuple[Card, ...]

Return a standard 52-card deck in deterministic order.

Source code in src/patiencepilot/cards.py
142
143
144
def standard_deck() -> tuple[Card, ...]:
    """Return a standard 52-card deck in deterministic order."""
    return tuple(Card(rank=rank, suit=suit) for suit in Suit for rank in Rank)

apply_move

apply_move(
    state: GameState,
    move: Move,
    variant: Variant | str | None = None,
) -> MoveResult

Apply move to state and return the resulting state and effects.

Source code in src/patiencepilot/engine.py
45
46
47
def apply_move(state: GameState, move: Move, variant: Variant | str | None = None) -> MoveResult:
    """Apply ``move`` to ``state`` and return the resulting state and effects."""
    return _resolve_variant(state, variant).apply_move(state, move)

is_won

is_won(
    state: GameState, variant: Variant | str | None = None
) -> bool

Return whether state is won.

Source code in src/patiencepilot/engine.py
50
51
52
def is_won(state: GameState, variant: Variant | str | None = None) -> bool:
    """Return whether ``state`` is won."""
    return _resolve_variant(state, variant).is_won(state)

legal_moves

legal_moves(
    state: GameState, variant: Variant | str | None = None
) -> tuple[Move, ...]

Return legal moves available from state.

Source code in src/patiencepilot/engine.py
40
41
42
def legal_moves(state: GameState, variant: Variant | str | None = None) -> tuple[Move, ...]:
    """Return legal moves available from ``state``."""
    return _resolve_variant(state, variant).legal_moves(state)

new_game

new_game(
    variant: Variant | str | None = None,
    seed: Seed = None,
    options: VariantOptions | None = None,
) -> GameState

Return a new game state.

Parameters:

Name Type Description Default
variant Variant | str | None

Rule set or registered variant name to use. Defaults to Klondike draw-one with unlimited redeals.

None
seed Seed

Optional deterministic random seed.

None
options VariantOptions | None

Variant options when variant is a name or omitted.

None
Source code in src/patiencepilot/engine.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
def new_game(
    variant: Variant | str | None = None,
    seed: Seed = None,
    options: VariantOptions | None = None,
) -> GameState:
    """Return a new game state.

    Args:
        variant: Rule set or registered variant name to use. Defaults to
            Klondike draw-one with unlimited redeals.
        seed: Optional deterministic random seed.
        options: Variant options when ``variant`` is a name or omitted.
    """
    rules = _coerce_variant(variant, options)
    return rules.new_game(seed=seed)

validate_state

validate_state(
    state: GameState, variant: Variant | str | None = None
) -> None

Validate that state is coherent for its variant.

Parameters:

Name Type Description Default
state GameState

State to validate.

required
variant Variant | str | None

Optional explicit rule set or registered variant name. When omitted, rules are resolved from state metadata.

None
Source code in src/patiencepilot/engine.py
29
30
31
32
33
34
35
36
37
def validate_state(state: GameState, variant: Variant | str | None = None) -> None:
    """Validate that ``state`` is coherent for its variant.

    Args:
        state: State to validate.
        variant: Optional explicit rule set or registered variant name. When
            omitted, rules are resolved from state metadata.
    """
    _resolve_variant(state, variant).validate_state(state)

deserialize_move

deserialize_move(data: Mapping[str, object]) -> Move

Return a move from a JSON-compatible serialized payload.

Parameters:

Name Type Description Default
data Mapping[str, object]

Mapping with an id string.

required

Raises:

Type Description
NotationError

If the payload is missing or has an invalid id.

Source code in src/patiencepilot/notation.py
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
def deserialize_move(data: Mapping[str, object]) -> Move:
    """Return a move from a JSON-compatible serialized payload.

    Args:
        data: Mapping with an ``id`` string.

    Raises:
        NotationError: If the payload is missing or has an invalid ``id``.
    """
    schema_version = data.get("schema_version", SCHEMA_VERSION)
    if schema_version != SCHEMA_VERSION:
        msg = f"unsupported move schema_version: {schema_version!r}"
        raise NotationError(msg)
    move_id = data.get("id")
    if not isinstance(move_id, str):
        msg = "serialized move must contain an 'id' string"
        raise NotationError(msg)
    return move_from_id(move_id)

deserialize_player_view

deserialize_player_view(
    data: Mapping[str, object],
) -> PlayerView

Return a player-known view from a JSON-compatible payload.

Source code in src/patiencepilot/notation.py
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
def deserialize_player_view(data: Mapping[str, object]) -> PlayerView:
    """Return a player-known view from a JSON-compatible payload."""
    schema_version = data.get("schema_version", SCHEMA_VERSION)
    if schema_version != SCHEMA_VERSION:
        msg = f"unsupported player-view schema_version: {schema_version!r}"
        raise NotationError(msg)

    options = _dict_value(data, "options")
    unknown = _mapping_value(data, "unknown")
    return PlayerView(
        foundations=_deserialize_foundations(data),
        tableau=_deserialize_player_tableau(data),
        waste=tuple(_deserialize_cards(data, "waste")),
        seen_cards=tuple(_deserialize_cards(data, "seen_cards")),
        unknown=UnknownCardConstraints(
            hidden_tableau_counts=tuple(_int_list_value(unknown, "hidden_tableau_counts")),
            stock_count=_int_value(unknown, "stock_count"),
            unseen_cards=tuple(_deserialize_cards(unknown, "unseen_cards")),
        ),
        variant=_str_value(data, "variant"),
        draw_count=_int_option(options, "draw_count", default=1),
        redeals_allowed=_optional_int_option(options, "redeals"),
        redeals_used=_int_value(data, "redeals_used"),
    )

deserialize_state

deserialize_state(data: Mapping[str, object]) -> GameState

Return a state from a JSON-compatible payload.

Parameters:

Name Type Description Default
data Mapping[str, object]

State payload created by :func:serialize_state.

required

Raises:

Type Description
NotationError

If the payload cannot be parsed or validated.

Source code in src/patiencepilot/notation.py
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
def deserialize_state(data: Mapping[str, object]) -> GameState:
    """Return a state from a JSON-compatible payload.

    Args:
        data: State payload created by :func:`serialize_state`.

    Raises:
        NotationError: If the payload cannot be parsed or validated.
    """
    migrated = migrate_state_payload(data)
    variant = _str_value(migrated, "variant")
    options = _dict_value(migrated, "options")
    state = GameState(
        foundations=_deserialize_foundations(migrated),
        tableau=_deserialize_tableau(migrated),
        stock=tuple(_deserialize_cards(migrated, "stock")),
        waste=tuple(_deserialize_cards(migrated, "waste")),
        variant=variant,
        draw_count=_int_option(options, "draw_count", default=1),
        redeals_allowed=_optional_int_option(options, "redeals"),
        redeals_used=_int_value(migrated, "redeals_used"),
    )
    _validate_state_with_options(state, options)
    return state

migrate_state_payload

migrate_state_payload(
    data: Mapping[str, object],
) -> dict[str, object]

Return a best-effort alpha migration to schema version 1.

Source code in src/patiencepilot/notation.py
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
def migrate_state_payload(data: Mapping[str, object]) -> dict[str, object]:
    """Return a best-effort alpha migration to schema version 1."""
    migrated = dict(data)
    schema_version = migrated.get("schema_version", SCHEMA_VERSION)
    if schema_version != SCHEMA_VERSION:
        msg = f"unsupported state schema_version: {schema_version!r}"
        raise NotationError(msg)
    migrated["schema_version"] = SCHEMA_VERSION
    migrated.setdefault("variant", "klondike")
    migrated.setdefault("options", {})
    migrated.setdefault("foundations", [[], [], [], []])
    migrated.setdefault("tableau", [])
    migrated.setdefault("stock", [])
    migrated.setdefault("waste", [])
    migrated.setdefault("redeals_used", 0)
    return migrated

move_from_id

move_from_id(move_id: str) -> Move

Parse a canonical compact move identifier.

Parameters:

Name Type Description Default
move_id str

Identifier such as DRAW, W->F, W->T3, T0->F, or T0->T3:2.

required

Raises:

Type Description
NotationError

If the identifier cannot be parsed.

Source code in src/patiencepilot/notation.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
def move_from_id(move_id: str) -> Move:
    """Parse a canonical compact move identifier.

    Args:
        move_id: Identifier such as ``DRAW``, ``W->F``, ``W->T3``,
            ``T0->F``, or ``T0->T3:2``.

    Raises:
        NotationError: If the identifier cannot be parsed.
    """
    normalized = _normalize_move_id(move_id)
    if normalized == "DRAW":
        return DrawFromStock()
    if normalized == "RECYCLE":
        return RecycleWaste()
    if normalized == "W->F":
        return WasteToFoundation()

    waste_to_tableau_match = _WASTE_TO_TABLEAU_RE.fullmatch(normalized)
    if waste_to_tableau_match is not None:
        return WasteToTableau(destination=int(waste_to_tableau_match.group("destination")))

    tableau_to_foundation_match = _TABLEAU_TO_FOUNDATION_RE.fullmatch(normalized)
    if tableau_to_foundation_match is not None:
        return TableauToFoundation(source=int(tableau_to_foundation_match.group("source")))

    tableau_to_tableau_match = _TABLEAU_TO_TABLEAU_RE.fullmatch(normalized)
    if tableau_to_tableau_match is not None:
        count_text = tableau_to_tableau_match.group("count")
        count = 1 if count_text is None else int(count_text)
        if count < 1:
            msg = f"tableau move count must be at least 1: {move_id!r}"
            raise NotationError(msg)
        return TableauToTableau(
            source=int(tableau_to_tableau_match.group("source")),
            destination=int(tableau_to_tableau_match.group("destination")),
            count=count,
        )

    msg = f"invalid move id: {move_id!r}"
    raise NotationError(msg)

move_to_id

move_to_id(move: Move) -> str

Return the canonical compact identifier for move.

Parameters:

Name Type Description Default
move Move

Structured move to identify.

required

Raises:

Type Description
NotationError

If the move contains invalid notation values.

Source code in src/patiencepilot/notation.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
def move_to_id(move: Move) -> str:
    """Return the canonical compact identifier for ``move``.

    Args:
        move: Structured move to identify.

    Raises:
        NotationError: If the move contains invalid notation values.
    """
    if isinstance(move, DrawFromStock):
        return "DRAW"
    if isinstance(move, RecycleWaste):
        return "RECYCLE"
    if isinstance(move, WasteToFoundation):
        return "W->F"
    if isinstance(move, WasteToTableau):
        _require_non_negative(move.destination, "destination")
        return f"W->T{move.destination}"
    if isinstance(move, TableauToFoundation):
        _require_non_negative(move.source, "source")
        return f"T{move.source}->F"
    if isinstance(move, TableauToTableau):
        _require_non_negative(move.source, "source")
        _require_non_negative(move.destination, "destination")
        if move.count < 1:
            msg = "tableau move count must be at least 1"
            raise NotationError(msg)
        suffix = "" if move.count == 1 else f":{move.count}"
        return f"T{move.source}->T{move.destination}{suffix}"

    msg = f"unsupported move: {move!r}"
    raise NotationError(msg)

serialize_move

serialize_move(move: Move) -> SerializedMove

Return a JSON-compatible serialized move payload.

Source code in src/patiencepilot/notation.py
194
195
196
def serialize_move(move: Move) -> SerializedMove:
    """Return a JSON-compatible serialized move payload."""
    return {"id": move_to_id(move)}

serialize_player_view

serialize_player_view(
    view: PlayerView,
) -> SerializedPlayerView

Return a JSON-compatible player-known state payload.

Source code in src/patiencepilot/notation.py
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
def serialize_player_view(view: PlayerView) -> SerializedPlayerView:
    """Return a JSON-compatible player-known state payload."""
    return {
        "schema_version": SCHEMA_VERSION,
        "variant": view.variant,
        "options": {
            "draw_count": view.draw_count,
            "redeals": view.redeals_allowed,
        },
        "foundations": [[card.code for card in foundation] for foundation in view.foundations],
        "tableau": [
            [
                {
                    "card": None if stack_card.card is None else stack_card.card.code,
                    "face_up": stack_card.face_up,
                }
                for stack_card in column
            ]
            for column in view.tableau
        ],
        "waste": [card.code for card in view.waste],
        "seen_cards": [card.code for card in view.seen_cards],
        "unknown": {
            "hidden_tableau_counts": list(view.unknown.hidden_tableau_counts),
            "stock_count": view.unknown.stock_count,
            "unseen_cards": [card.code for card in view.unknown.unseen_cards],
        },
        "redeals_used": view.redeals_used,
    }

serialize_state

serialize_state(state: GameState) -> SerializedGameState

Return a JSON-compatible authoritative state payload.

Source code in src/patiencepilot/notation.py
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
def serialize_state(state: GameState) -> SerializedGameState:
    """Return a JSON-compatible authoritative state payload."""
    return {
        "schema_version": SCHEMA_VERSION,
        "variant": state.variant,
        "options": variant_options_from_state(state),
        "foundations": [[card.code for card in foundation] for foundation in state.foundations],
        "tableau": [
            [{"card": stack_card.card.code, "face_up": stack_card.face_up} for stack_card in column]
            for column in state.tableau
        ],
        "stock": [card.code for card in state.stock],
        "waste": [card.code for card in state.waste],
        "redeals_used": state.redeals_used,
    }

state_from_text

state_from_text(text: str) -> GameState

Return a state parsed from canonical text notation.

Parameters:

Name Type Description Default
text str

State notation produced by :func:state_to_text.

required

Raises:

Type Description
NotationError

If the notation cannot be parsed or validated.

Source code in src/patiencepilot/notation.py
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
def state_from_text(text: str) -> GameState:
    """Return a state parsed from canonical text notation.

    Args:
        text: State notation produced by :func:`state_to_text`.

    Raises:
        NotationError: If the notation cannot be parsed or validated.
    """
    lines = _normalized_state_lines(text)
    if len(lines) < 4:
        msg = "state notation must contain variant, foundations, stock, waste, and tableau lines"
        raise NotationError(msg)

    variant, options, redeals_used = _parse_variant_line(lines[0])
    foundations = _parse_foundations_line(lines[1])
    stock = _parse_card_sequence_line(lines[2], "STOCK")
    waste = _parse_card_sequence_line(lines[3], "WASTE")
    tableau = tuple(_parse_tableau_line(line, expected_index=index) for index, line in enumerate(lines[4:]))

    state = GameState(
        foundations=foundations,
        tableau=tableau,
        stock=stock,
        waste=waste,
        variant=variant,
        draw_count=_int_option(options, "draw_count", default=1),
        redeals_allowed=_optional_int_option(options, "redeals"),
        redeals_used=redeals_used,
    )
    _validate_state_with_options(state, options)
    return state

state_to_text

state_to_text(state: GameState) -> str

Return canonical text notation for an authoritative state.

Source code in src/patiencepilot/notation.py
219
220
221
222
223
224
225
226
227
228
229
230
231
def state_to_text(state: GameState) -> str:
    """Return canonical text notation for an authoritative state."""
    redeals = "none" if state.redeals_allowed is None else str(state.redeals_allowed)
    lines = [
        f"VARIANT {state.variant} draw_count={state.draw_count} redeals={redeals} redeals_used={state.redeals_used}",
        "FOUNDATIONS " + " ".join(f"{suit.code}={_format_card_codes(state.foundation(suit))}" for suit in SUIT_ORDER),
        f"STOCK: {_format_card_sequence(state.stock)}",
        f"WASTE: {_format_card_sequence(state.waste)}",
    ]
    lines.extend(
        f"T{column_index}: {_format_tableau_column(column)}" for column_index, column in enumerate(state.tableau)
    )
    return "\n".join(lines)

validate_move_id

validate_move_id(move_id: str) -> ValidationResult

Validate a move identifier without raising.

Source code in src/patiencepilot/notation.py
386
387
388
389
390
391
392
def validate_move_id(move_id: str) -> ValidationResult:
    """Validate a move identifier without raising."""
    try:
        move_from_id(move_id)
    except PatiencePilotError as error:
        return _validation_result("move_id", error)
    return ValidationResult()

validate_serialized_move

validate_serialized_move(
    data: Mapping[str, object],
) -> ValidationResult

Validate a serialized move payload without raising.

Source code in src/patiencepilot/notation.py
395
396
397
398
399
400
401
def validate_serialized_move(data: Mapping[str, object]) -> ValidationResult:
    """Validate a serialized move payload without raising."""
    try:
        deserialize_move(data)
    except PatiencePilotError as error:
        return _validation_result("move", error)
    return ValidationResult()

validate_serialized_state

validate_serialized_state(
    data: Mapping[str, object],
) -> ValidationResult

Validate a serialized state payload without raising.

Source code in src/patiencepilot/notation.py
404
405
406
407
408
409
410
def validate_serialized_state(data: Mapping[str, object]) -> ValidationResult:
    """Validate a serialized state payload without raising."""
    try:
        deserialize_state(data)
    except PatiencePilotError as error:
        return _validation_result("state", error)
    return ValidationResult()

validate_state_text

validate_state_text(text: str) -> ValidationResult

Validate state text notation without raising.

Source code in src/patiencepilot/notation.py
413
414
415
416
417
418
419
def validate_state_text(text: str) -> ValidationResult:
    """Validate state text notation without raising."""
    try:
        state_from_text(text)
    except PatiencePilotError as error:
        return _validation_result("state_text", error)
    return ValidationResult()

resolve_solver

resolve_solver(
    name: str = "dummy",
    *,
    registry: SolverRegistry | None = None,
) -> AdviceProvider

Return an advice provider for a registered solver name.

Parameters:

Name Type Description Default
name str

Solver name or alias. Defaults to "dummy".

'dummy'
registry SolverRegistry | None

Registry to use. Defaults to the package registry.

None
Source code in src/patiencepilot/solvers/registry.py
 93
 94
 95
 96
 97
 98
 99
100
def resolve_solver(name: str = "dummy", *, registry: SolverRegistry | None = None) -> AdviceProvider:
    """Return an advice provider for a registered solver name.

    Args:
        name: Solver name or alias. Defaults to ``"dummy"``.
        registry: Registry to use. Defaults to the package registry.
    """
    return _registry_or_default(registry).create(name)

solver_names

solver_names(
    *, registry: SolverRegistry | None = None
) -> tuple[str, ...]

Return canonical names of registered solvers.

Source code in src/patiencepilot/solvers/registry.py
103
104
105
def solver_names(*, registry: SolverRegistry | None = None) -> tuple[str, ...]:
    """Return canonical names of registered solvers."""
    return _registry_or_default(registry).names

visible_klondike_moves

visible_klondike_moves(
    view: PlayerView,
) -> tuple[Move, ...]

Return Klondike moves legal from player-visible state.

Source code in src/patiencepilot/solvers/dummy.py
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def visible_klondike_moves(view: PlayerView) -> tuple[Move, ...]:
    """Return Klondike moves legal from player-visible state."""
    if view.variant != "klondike":
        msg = f"dummy solver only supports 'klondike', got {view.variant!r}"
        raise UnsupportedVariantError(msg)

    moves: list[Move] = []
    if view.stock_count:
        moves.append(DrawFromStock())
    elif view.waste and _can_recycle(view):
        moves.append(RecycleWaste())

    if view.waste:
        waste_card = view.waste[-1]
        if _can_move_to_foundation(waste_card, view.foundation(waste_card.suit)):
            moves.append(WasteToFoundation())
        for destination in range(N_TABLEAU_COLUMNS):
            if _can_place_on_tableau(waste_card, view.tableau[destination]):
                moves.append(WasteToTableau(destination=destination))

    for source, column in enumerate(view.tableau):
        top_card = _top_visible_card(column)
        if top_card is not None and _can_move_to_foundation(top_card, view.foundation(top_card.suit)):
            moves.append(TableauToFoundation(source=source))

        for start_index in range(len(column)):
            moving_stack = column[start_index:]
            if not _is_movable_tableau_stack(moving_stack):
                continue
            moving_card = moving_stack[0].visible_card
            if moving_card is None:
                continue
            count = len(moving_stack)
            for destination in range(N_TABLEAU_COLUMNS):
                if source == destination:
                    continue
                if _can_place_on_tableau(moving_card, view.tableau[destination]):
                    moves.append(TableauToTableau(source=source, destination=destination, count=count))

    return tuple(moves)

resolve_state_variant

resolve_state_variant(
    state: GameState,
    *,
    registry: VariantRegistry | None = None,
) -> Variant

Return rules for the variant metadata stored in state.

Parameters:

Name Type Description Default
state GameState

State containing variant name and option metadata.

required
registry VariantRegistry | None

Registry to use. Defaults to the package registry.

None
Source code in src/patiencepilot/variants/registry.py
142
143
144
145
146
147
148
149
def resolve_state_variant(state: GameState, *, registry: VariantRegistry | None = None) -> Variant:
    """Return rules for the variant metadata stored in ``state``.

    Args:
        state: State containing variant name and option metadata.
        registry: Registry to use. Defaults to the package registry.
    """
    return _registry_or_default(registry).resolve_state(state)

resolve_variant

resolve_variant(
    name: str = KlondikeRules.name,
    options: VariantOptions | None = None,
    *,
    registry: VariantRegistry | None = None,
) -> Variant

Return rules for a registered variant name and options.

Parameters:

Name Type Description Default
name str

Variant name or alias. Defaults to "klondike".

name
options VariantOptions | None

Variant-specific configuration values.

None
registry VariantRegistry | None

Registry to use. Defaults to the package registry.

None
Source code in src/patiencepilot/variants/registry.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
def resolve_variant(
    name: str = KlondikeRules.name,
    options: VariantOptions | None = None,
    *,
    registry: VariantRegistry | None = None,
) -> Variant:
    """Return rules for a registered variant name and options.

    Args:
        name: Variant name or alias. Defaults to ``"klondike"``.
        options: Variant-specific configuration values.
        registry: Registry to use. Defaults to the package registry.
    """
    return _registry_or_default(registry).resolve(name, options)

variant_names

variant_names(
    *, registry: VariantRegistry | None = None
) -> tuple[str, ...]

Return canonical names of registered variants.

Source code in src/patiencepilot/variants/registry.py
162
163
164
def variant_names(*, registry: VariantRegistry | None = None) -> tuple[str, ...]:
    """Return canonical names of registered variants."""
    return _registry_or_default(registry).names

variant_options_from_state

variant_options_from_state(
    state: GameState,
    *,
    registry: VariantRegistry | None = None,
) -> dict[str, object]

Return registry options that reproduce state rules.

Parameters:

Name Type Description Default
state GameState

State containing variant name and option metadata.

required
registry VariantRegistry | None

Registry to use. Defaults to the package registry.

None
Source code in src/patiencepilot/variants/registry.py
152
153
154
155
156
157
158
159
def variant_options_from_state(state: GameState, *, registry: VariantRegistry | None = None) -> dict[str, object]:
    """Return registry options that reproduce ``state`` rules.

    Args:
        state: State containing variant name and option metadata.
        registry: Registry to use. Defaults to the package registry.
    """
    return _registry_or_default(registry).options_from_state(state)