Skip to content

Notation

patiencepilot.notation

Canonical notation and JSON-compatible serialization.

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]

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

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

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

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]

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

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.

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)

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)

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)}

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)

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)

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

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,
    }

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

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,
    }

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"),
    )

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()