Skip to content

Tui

patiencepilot.ui.tui

Textual terminal user interface.

TuiOptions dataclass

Configuration for launching the TUI.

Source code in src/patiencepilot/ui/tui.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
@dataclass(frozen=True, slots=True)
class TuiOptions:
    """Configuration for launching the TUI."""

    seed: Seed = None
    draw_count: int = 1
    redeals: int | None = None
    load_path: Path | None = None
    save_path: Path | None = None
    real_world: bool = False
    solver: str = "dummy"
    advice_time_limit: float | None = None
    advice_node_limit: int | None = None
    advice_depth_limit: int | None = 1

KnownStep dataclass

One move applied to a player-known real-world mirror session.

Source code in src/patiencepilot/ui/tui.py
59
60
61
62
63
64
65
@dataclass(frozen=True, slots=True)
class KnownStep:
    """One move applied to a player-known real-world mirror session."""

    move: Move
    before: PlayerView
    after: PlayerView

KnownGameSession dataclass

Mutable TUI session for mirroring a real-world player-known state.

Source code in src/patiencepilot/ui/tui.py
68
69
70
71
72
73
74
75
76
77
78
79
@dataclass(slots=True)
class KnownGameSession:
    """Mutable TUI session for mirroring a real-world player-known state."""

    view: PlayerView
    history: list[KnownStep] = field(default_factory=list)
    redo: list[KnownStep] = field(default_factory=list)

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

move_history property

move_history: tuple[Move, ...]

Return applied move history.

RealWorldSetup dataclass

Guided initial setup state for a real-world Klondike game.

Source code in src/patiencepilot/ui/tui.py
82
83
84
85
86
@dataclass(slots=True)
class RealWorldSetup:
    """Guided initial setup state for a real-world Klondike game."""

    tableau_cards: list[Card] = field(default_factory=list)

RealWorldPrompt dataclass

Prompt requiring user-entered newly visible card identities.

Source code in src/patiencepilot/ui/tui.py
89
90
91
92
93
94
95
96
97
98
@dataclass(slots=True)
class RealWorldPrompt:
    """Prompt requiring user-entered newly visible card identities."""

    kind: str
    message: str
    move: Move
    before: PlayerView
    interim: PlayerView | None = None
    count: int = 1

PatiencePilotTui

Bases: App[None]

Interactive Textual application for playing Solitaire.

Source code in src/patiencepilot/ui/tui.py
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
class PatiencePilotTui(App[None]):
    """Interactive Textual application for playing Solitaire."""

    CSS = """
    Screen {
        background: #0d1117;
        color: #f0f6fc;
    }

    #layout {
        height: 1fr;
        padding: 1;
    }

    #board-panel {
        width: 1fr;
        min-width: 34;
        padding: 1;
        border: round #2f81f7;
        background: #111827;
    }

    #side-panel {
        width: 1fr;
        min-width: 38;
        padding: 1;
        border: round #3fb950;
        background: #0f172a;
    }

    .panel-title {
        text-style: bold;
        color: #79c0ff;
        margin-bottom: 1;
    }

    #board {
        height: 1fr;
        color: #e6edf3;
    }

    #move-input {
        margin: 0 0 1 0;
    }

    #buttons {
        height: 8;
        margin-bottom: 1;
    }

    .button-row {
        height: 4;
    }

    #status {
        height: 4;
        margin-top: 1;
        color: #ffa657;
    }

    #legal-moves {
        height: 1fr;
        margin-top: 1;
        padding: 1;
        border: tall #30363d;
        background: #0b1220;
    }

    #history {
        height: 6;
        margin-top: 1;
        padding: 1;
        border: tall #30363d;
        color: #c9d1d9;
    }

    Button {
        width: 1fr;
        min-width: 7;
        margin: 1 1 0 0;
    }

    Button.primary {
        background: #238636;
    }

    Button.warning {
        background: #9e6a03;
    }
    """

    BINDINGS: ClassVar[list[BindingType]] = [
        ("d", "quick_draw", "Draw"),
        ("u", "undo", "Undo"),
        ("r", "redo", "Redo"),
        ("n", "new_game", "New"),
        ("s", "save", "Save"),
        ("q", "quit", "Quit"),
    ]

    def __init__(
        self,
        options: TuiOptions | None = None,
        *,
        app_service: PatiencePilotApp | None = None,
    ) -> None:
        """Initialize the TUI app."""
        super().__init__()
        self.options = TuiOptions() if options is None else options
        self.service = PatiencePilotApp() if app_service is None else app_service
        if self.service.advice_provider is None:
            self.service.select_solver(self.options.solver)
        self._last_effects: tuple[MoveEffect, ...] = ()
        self._status = "Ready."
        self._known_session: KnownGameSession | None = None
        self._real_world_setup: RealWorldSetup | None = None
        self._real_world_prompt: RealWorldPrompt | None = None

    def compose(self) -> ComposeResult:
        """Compose the terminal layout."""
        yield Header(show_clock=True)
        with Horizontal(id="layout"):
            with Vertical(id="board-panel"):
                yield Static("Patience Pilot", classes="panel-title")
                yield Static("", id="board")
            with Vertical(id="side-panel"):
                yield Static("Controls", classes="panel-title")
                with Vertical(id="buttons"):
                    with Horizontal(classes="button-row"):
                        yield Button("Apply", id="apply", variant="success", classes="primary")
                        yield Button("Draw", id="draw")
                        yield Button("Undo", id="undo")
                        yield Button("Redo", id="redo")
                    with Horizontal(classes="button-row"):
                        yield Button("New", id="new", variant="primary")
                        yield Button("Save", id="save")
                        yield Button("Load", id="load")
                        yield Button("Advice", id="advice", classes="warning")
                yield Input(placeholder="Move ID or number, e.g., DRAW or 2", id="move-input")
                yield Static("", id="legal-moves")
                yield Static("", id="history")
                yield Static("", id="status")
        yield Footer()

    def on_mount(self) -> None:
        """Start or load a game when the TUI mounts."""
        if self.options.real_world:
            self._start_real_world_setup()
        else:
            self._load_or_start_session()
        self._refresh()
        self.query_one("#move-input", Input).focus()

    def on_button_pressed(self, event: Button.Pressed) -> None:
        """Handle control button presses."""
        button_id = event.button.id
        if button_id == "apply":
            self._apply_entered_move()
        elif button_id == "draw":
            self.action_quick_draw()
        elif button_id == "undo":
            self.action_undo()
        elif button_id == "redo":
            self.action_redo()
        elif button_id == "new":
            self.action_new_game()
        elif button_id == "save":
            self.action_save()
        elif button_id == "load":
            self.action_load()
        elif button_id == "advice":
            self._request_advice()

    def on_input_submitted(self, event: Input.Submitted) -> None:
        """Apply an entered move ID."""
        if event.input.id == "move-input":
            self._apply_entered_move()

    def action_quick_draw(self) -> None:
        """Apply DRAW or RECYCLE when either is legal."""
        if self._is_real_world_mode:
            self._apply_known_quick_draw()
            return
        legal_ids = tuple(move_to_id(move) for move in self.session.legal_moves())
        if "DRAW" in legal_ids:
            self._apply_move_id("DRAW")
        elif "RECYCLE" in legal_ids:
            self._apply_move_id("RECYCLE")
        else:
            self._set_status("No draw or recycle move is currently legal.")

    def action_undo(self) -> None:
        """Undo the latest move."""
        if self._is_real_world_mode:
            self._undo_known_move()
            return
        try:
            step = self.session.undo()
        except PatiencePilotError as error:
            self._set_status(str(error))
            return
        self._last_effects = ()
        self._set_status(f"Undid {move_to_id(step.move)}.")

    def action_redo(self) -> None:
        """Redo the latest undone move."""
        if self._is_real_world_mode:
            self._redo_known_move()
            return
        try:
            result = self.session.redo()
        except PatiencePilotError as error:
            self._set_status(str(error))
            return
        self._last_effects = result.effects
        self._set_status(f"Redid {move_to_id(result.move)}.")

    def action_new_game(self) -> None:
        """Start a new game."""
        if self._is_real_world_mode:
            self._start_real_world_setup()
            self._last_effects = ()
            self._set_status("Started real-world setup.")
            return
        self._start_new_session()
        self._last_effects = ()
        self._set_status("Started a new game.")

    def action_save(self) -> None:
        """Save the active session."""
        if self._is_real_world_mode:
            self._set_status("Saving real-world mirror sessions is not yet supported.")
            return
        if self.options.save_path is None:
            self._set_status("Start with --save PATH to enable saving.")
            return
        try:
            self._write_session(self.options.save_path)
        except OSError as error:
            self._set_status(str(error))
            return
        self._set_status(f"Saved to {self.options.save_path}.")

    def action_load(self) -> None:
        """Load the configured session path."""
        if self._is_real_world_mode:
            self._set_status("Loading real-world mirror sessions is not yet supported.")
            return
        path = self.options.load_path or self.options.save_path
        if path is None:
            self._set_status("Start with --load PATH to enable loading.")
            return
        try:
            self.service.import_session(_read_json_object(path))
        except (OSError, json.JSONDecodeError, PatiencePilotError, ValueError) as error:
            self._set_status(str(error))
            return
        self._last_effects = ()
        self._set_status(f"Loaded {path}.")

    @property
    def session(self) -> GameSession:
        """Return the active session."""
        if self.service.session is None:
            self._start_new_session()
        if self.service.session is None:
            msg = "no active session"
            raise RuntimeError(msg)
        return self.service.session

    def _load_or_start_session(self) -> None:
        """Load a saved session or start a new one."""
        if self.options.load_path is not None:
            try:
                self.service.import_session(_read_json_object(self.options.load_path))
            except (OSError, json.JSONDecodeError, PatiencePilotError, ValueError) as error:
                self._status = f"Could not load {self.options.load_path}: {error}. Started a new game."
                self._start_new_session()
            return
        if self.service.session is not None:
            return
        self._start_new_session()

    def _start_new_session(self) -> None:
        """Start a new session from launch options."""
        self.service.select_variant(
            "klondike",
            {"draw_count": self.options.draw_count, "redeals": self.options.redeals},
        )
        self.service.new_session(seed=self.options.seed)

    @property
    def _is_real_world_mode(self) -> bool:
        """Return whether the TUI is mirroring player-known real-world state."""
        return self.options.real_world or self._known_session is not None or self._real_world_setup is not None

    def _start_real_world_setup(self) -> None:
        """Start guided setup for a physical-card Klondike game."""
        self._known_session = None
        self._real_world_prompt = None
        self._real_world_setup = RealWorldSetup()
        self._last_effects = ()
        self._status = "Enter the visible card on T0, e.g. AS."
        self._set_input_placeholder("Visible T0 card, e.g. AS")

    def _apply_entered_move(self) -> None:
        """Apply the current move input value."""
        move_input = self.query_one("#move-input", Input).value.strip()
        if not move_input:
            self._set_status("Enter a move ID first.")
            return
        if self._is_real_world_mode:
            self._handle_real_world_input(move_input)
            return
        try:
            move_id = _move_id_from_input(self.session, move_input)
        except ValueError as error:
            self._set_status(str(error))
            return
        self._apply_move_id(move_id)

    def _apply_move_id(self, move_id: str) -> None:
        """Apply a move by ID."""
        try:
            move = move_from_id(move_id)
            result = self.service.apply_move(move)
        except PatiencePilotError as error:
            self._set_status(str(error))
            return
        self._last_effects = result.effects
        self.query_one("#move-input", Input).value = ""
        if self.session.is_won():
            self._set_status(f"Applied {move_to_id(move)}. You won!")
        else:
            self._set_status(f"Applied {move_to_id(move)}.")

    def _request_advice(self) -> None:
        """Ask the configured advice provider for a move."""
        if self._is_real_world_mode:
            self._request_known_advice()
            return
        try:
            advice = self.service.request_advice(limit=self._advice_limit())
        except PatiencePilotError as error:
            self._set_status(str(error))
            return
        best_move = advice.best_move
        if best_move is None:
            self._set_status("No advice available.")
            return
        self.query_one("#move-input", Input).value = move_to_id(best_move)
        self._set_status(f"Advice: try {move_to_id(best_move)}.")

    def _handle_real_world_input(self, text: str) -> None:
        """Handle setup, prompt, or move input for a real-world mirror game."""
        if self._real_world_setup is not None:
            self._add_real_world_setup_card(text)
            return
        if self._real_world_prompt is not None:
            self._complete_real_world_prompt(text)
            return
        self._apply_known_entered_move(text)

    def _add_real_world_setup_card(self, text: str) -> None:
        """Add one visible tableau card during real-world setup."""
        setup = self._real_world_setup
        if setup is None:
            return
        column = len(setup.tableau_cards)
        try:
            card = _parse_one_card(text)
            _validate_no_duplicate_cards((*setup.tableau_cards, card))
        except ValueError as error:
            self._set_status(str(error))
            return

        setup.tableau_cards.append(card)
        self.query_one("#move-input", Input).value = ""
        if len(setup.tableau_cards) == 7:
            view = _new_real_world_view(
                setup.tableau_cards,
                draw_count=self.options.draw_count,
                redeals=self.options.redeals,
            )
            self._known_session = KnownGameSession(view=view)
            self._real_world_setup = None
            self._set_input_placeholder("Move ID or number, e.g., DRAW or 2")
            self._set_status("Real-world mirror ready. Enter a move or ask for advice.")
            return

        next_column = column + 1
        self._set_input_placeholder(f"Visible T{next_column} card, e.g. 7D")
        self._set_status(f"Recorded T{column}={card.code}. Enter the visible card on T{next_column}.")

    def _complete_real_world_prompt(self, text: str) -> None:
        """Complete an active real-world prompt with newly observed cards."""
        prompt = self._real_world_prompt
        if prompt is None:
            return
        try:
            if prompt.kind == "draw":
                cards = _parse_card_list(text)
                if len(cards) != prompt.count:
                    msg = f"Enter exactly {prompt.count} drawn card(s)."
                    raise ValueError(msg)
                _validate_new_visible_cards(cards, prompt.before)
                after = _replace_player_view(
                    prompt.before,
                    stock_count=prompt.before.stock_count - prompt.count,
                    waste=(*prompt.before.waste, *cards),
                    extra_seen=cards,
                )
                self._real_world_prompt = None
                self._commit_known_step(prompt.move, prompt.before, after, f"Applied {move_to_id(prompt.move)}.")
                return

            if prompt.kind == "reveal" and prompt.interim is not None:
                card = _parse_one_card(text)
                _validate_revealed_tableau_card(card, prompt.interim)
                after = _reveal_pending_tableau_card(prompt.interim, prompt.move, card)
                self._real_world_prompt = None
                status = f"Applied {move_to_id(prompt.move)} and revealed {card.code}."
                self._commit_known_step(prompt.move, prompt.before, after, status)
                return
        except ValueError as error:
            self._set_status(str(error))
            return

        self._set_status("No real-world prompt is active.")

    def _apply_known_entered_move(self, text: str) -> None:
        """Apply the current input as a move against player-known state."""
        known = self._known_session
        if known is None:
            self._set_status("Finish real-world setup first.")
            return
        try:
            move_id = _known_move_id_from_input(known.view, text)
            move = move_from_id(move_id)
            self._apply_known_move(move)
        except (PatiencePilotError, ValueError) as error:
            self._set_status(str(error))

    def _apply_known_move(self, move: Move) -> None:
        """Apply a visible-legal move to the player-known session."""
        known = self._known_session
        if known is None:
            self._set_status("Finish real-world setup first.")
            return
        legal_moves = visible_klondike_moves(known.view)
        if move not in legal_moves:
            self._set_status(f"{move_to_id(move)} is not legal from the visible state.")
            return

        if isinstance(move, DrawFromStock):
            count = min(known.view.draw_count, known.view.stock_count)
            self._real_world_prompt = RealWorldPrompt(
                kind="draw",
                message=_draw_prompt_message(count),
                move=move,
                before=known.view,
                count=count,
            )
            self.query_one("#move-input", Input).value = ""
            self._set_input_placeholder(_draw_input_placeholder(count))
            self._set_status(_draw_prompt_message(count))
            return

        before = known.view
        after, reveal_column = _apply_known_immediate_move(before, move)
        self.query_one("#move-input", Input).value = ""
        if reveal_column is not None:
            message = f"Enter the newly revealed card on T{reveal_column}."
            self._real_world_prompt = RealWorldPrompt(
                kind="reveal",
                message=message,
                move=move,
                before=before,
                interim=after,
            )
            self._set_input_placeholder(f"Revealed T{reveal_column} card, e.g. 2C")
            self._set_status(message)
            return
        self._commit_known_step(move, before, after, f"Applied {move_to_id(move)}.")

    def _apply_known_quick_draw(self) -> None:
        """Apply DRAW or RECYCLE in a player-known session when possible."""
        known = self._known_session
        if known is None:
            self._set_status("Finish real-world setup first.")
            return
        legal_moves = visible_klondike_moves(known.view)
        for wanted in (DrawFromStock(), RecycleWaste()):
            if wanted in legal_moves:
                self._apply_known_move(wanted)
                return
        self._set_status("No draw or recycle move is currently legal.")

    def _undo_known_move(self) -> None:
        """Undo the latest real-world mirror move."""
        if self._real_world_prompt is not None:
            self._set_status("Enter the requested card before undoing.")
            return
        known = self._known_session
        if known is None or not known.history:
            self._set_status("no moves to undo")
            return
        step = known.history.pop()
        known.redo.append(step)
        known.view = step.before
        self._last_effects = ()
        self._set_status(f"Undid {move_to_id(step.move)}.")

    def _redo_known_move(self) -> None:
        """Redo the latest undone real-world mirror move."""
        if self._real_world_prompt is not None:
            self._set_status("Enter the requested card before redoing.")
            return
        known = self._known_session
        if known is None or not known.redo:
            self._set_status("no moves to redo")
            return
        step = known.redo.pop()
        known.history.append(step)
        known.view = step.after
        self._last_effects = ()
        self._set_status(f"Redid {move_to_id(step.move)}.")

    def _commit_known_step(self, move: Move, before: PlayerView, after: PlayerView, status: str) -> None:
        """Record a completed real-world mirror move."""
        known = self._known_session
        if known is None:
            return
        known.view = after
        known.history.append(KnownStep(move=move, before=before, after=after))
        known.redo.clear()
        self._last_effects = ()
        self.query_one("#move-input", Input).value = ""
        self._set_input_placeholder("Move ID or number, e.g., DRAW or 2")
        self._set_status(status)

    def _request_known_advice(self) -> None:
        """Ask the advice provider for a move from player-known state."""
        if self._real_world_prompt is not None:
            self._set_status("Enter the requested card before asking for advice.")
            return
        known = self._known_session
        if known is None:
            self._set_status("Finish real-world setup first.")
            return
        if self.service.advice_provider is None:
            self._set_status("No advice provider configured.")
            return
        try:
            advice = self.service.advice_provider.suggest(known.view, limit=self._advice_limit())
        except PatiencePilotError as error:
            self._set_status(str(error))
            return
        best_move = advice.best_move
        if best_move is None:
            self._set_status("No advice available.")
            return
        self.query_one("#move-input", Input).value = move_to_id(best_move)
        self._set_status(f"Advice: try {move_to_id(best_move)}.")

    def _advice_limit(self) -> SearchLimit | None:
        """Return configured solver search limits."""
        if (
            self.options.advice_time_limit is None
            and self.options.advice_node_limit is None
            and self.options.advice_depth_limit is None
        ):
            return None
        return SearchLimit(
            time_seconds=self.options.advice_time_limit,
            node_limit=self.options.advice_node_limit,
            depth_limit=self.options.advice_depth_limit,
        )

    def _write_session(self, path: Path) -> None:
        """Write the current session to ``path``."""
        path.write_text(json.dumps(self.service.export_session(), indent=2, sort_keys=True) + "\n", encoding="utf-8")

    def _set_status(self, message: str) -> None:
        """Set status text and refresh the display."""
        self._status = message
        self._refresh()

    def _set_input_placeholder(self, placeholder: str) -> None:
        """Set the move input placeholder when the input is mounted."""
        self.query_one("#move-input", Input).placeholder = placeholder

    def _refresh(self) -> None:
        """Refresh all dynamic widgets."""
        if self._real_world_setup is not None:
            self.query_one("#board", Static).update(render_real_world_setup(self._real_world_setup))
            self.query_one("#legal-moves", Static).update("Legal moves\n\nFinish setup to see legal moves.")
            self.query_one("#history", Static).update("History\n\nNo moves yet.")
            self.query_one("#status", Static).update(render_status(self._status, self._last_effects))
            return
        if self._known_session is not None:
            self.query_one("#board", Static).update(render_player_view(self._known_session.view))
            self.query_one("#legal-moves", Static).update(render_known_legal_moves(self._known_session.view))
            self.query_one("#history", Static).update(render_known_history(self._known_session))
            self.query_one("#status", Static).update(render_status(self._status, self._last_effects))
            return
        session = self.session
        self.query_one("#board", Static).update(render_board(session))
        self.query_one("#legal-moves", Static).update(render_legal_moves(session))
        self.query_one("#history", Static).update(render_history(session))
        self.query_one("#status", Static).update(render_status(self._status, self._last_effects))

session property

session: GameSession

Return the active session.

__init__

__init__(
    options: TuiOptions | None = None,
    *,
    app_service: PatiencePilotApp | None = None,
) -> None

Initialize the TUI app.

Source code in src/patiencepilot/ui/tui.py
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
def __init__(
    self,
    options: TuiOptions | None = None,
    *,
    app_service: PatiencePilotApp | None = None,
) -> None:
    """Initialize the TUI app."""
    super().__init__()
    self.options = TuiOptions() if options is None else options
    self.service = PatiencePilotApp() if app_service is None else app_service
    if self.service.advice_provider is None:
        self.service.select_solver(self.options.solver)
    self._last_effects: tuple[MoveEffect, ...] = ()
    self._status = "Ready."
    self._known_session: KnownGameSession | None = None
    self._real_world_setup: RealWorldSetup | None = None
    self._real_world_prompt: RealWorldPrompt | None = None

compose

compose() -> ComposeResult

Compose the terminal layout.

Source code in src/patiencepilot/ui/tui.py
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
def compose(self) -> ComposeResult:
    """Compose the terminal layout."""
    yield Header(show_clock=True)
    with Horizontal(id="layout"):
        with Vertical(id="board-panel"):
            yield Static("Patience Pilot", classes="panel-title")
            yield Static("", id="board")
        with Vertical(id="side-panel"):
            yield Static("Controls", classes="panel-title")
            with Vertical(id="buttons"):
                with Horizontal(classes="button-row"):
                    yield Button("Apply", id="apply", variant="success", classes="primary")
                    yield Button("Draw", id="draw")
                    yield Button("Undo", id="undo")
                    yield Button("Redo", id="redo")
                with Horizontal(classes="button-row"):
                    yield Button("New", id="new", variant="primary")
                    yield Button("Save", id="save")
                    yield Button("Load", id="load")
                    yield Button("Advice", id="advice", classes="warning")
            yield Input(placeholder="Move ID or number, e.g., DRAW or 2", id="move-input")
            yield Static("", id="legal-moves")
            yield Static("", id="history")
            yield Static("", id="status")
    yield Footer()

on_mount

on_mount() -> None

Start or load a game when the TUI mounts.

Source code in src/patiencepilot/ui/tui.py
245
246
247
248
249
250
251
252
def on_mount(self) -> None:
    """Start or load a game when the TUI mounts."""
    if self.options.real_world:
        self._start_real_world_setup()
    else:
        self._load_or_start_session()
    self._refresh()
    self.query_one("#move-input", Input).focus()

on_button_pressed

on_button_pressed(event: Pressed) -> None

Handle control button presses.

Source code in src/patiencepilot/ui/tui.py
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
def on_button_pressed(self, event: Button.Pressed) -> None:
    """Handle control button presses."""
    button_id = event.button.id
    if button_id == "apply":
        self._apply_entered_move()
    elif button_id == "draw":
        self.action_quick_draw()
    elif button_id == "undo":
        self.action_undo()
    elif button_id == "redo":
        self.action_redo()
    elif button_id == "new":
        self.action_new_game()
    elif button_id == "save":
        self.action_save()
    elif button_id == "load":
        self.action_load()
    elif button_id == "advice":
        self._request_advice()

on_input_submitted

on_input_submitted(event: Submitted) -> None

Apply an entered move ID.

Source code in src/patiencepilot/ui/tui.py
274
275
276
277
def on_input_submitted(self, event: Input.Submitted) -> None:
    """Apply an entered move ID."""
    if event.input.id == "move-input":
        self._apply_entered_move()

action_quick_draw

action_quick_draw() -> None

Apply DRAW or RECYCLE when either is legal.

Source code in src/patiencepilot/ui/tui.py
279
280
281
282
283
284
285
286
287
288
289
290
def action_quick_draw(self) -> None:
    """Apply DRAW or RECYCLE when either is legal."""
    if self._is_real_world_mode:
        self._apply_known_quick_draw()
        return
    legal_ids = tuple(move_to_id(move) for move in self.session.legal_moves())
    if "DRAW" in legal_ids:
        self._apply_move_id("DRAW")
    elif "RECYCLE" in legal_ids:
        self._apply_move_id("RECYCLE")
    else:
        self._set_status("No draw or recycle move is currently legal.")

action_undo

action_undo() -> None

Undo the latest move.

Source code in src/patiencepilot/ui/tui.py
292
293
294
295
296
297
298
299
300
301
302
303
def action_undo(self) -> None:
    """Undo the latest move."""
    if self._is_real_world_mode:
        self._undo_known_move()
        return
    try:
        step = self.session.undo()
    except PatiencePilotError as error:
        self._set_status(str(error))
        return
    self._last_effects = ()
    self._set_status(f"Undid {move_to_id(step.move)}.")

action_redo

action_redo() -> None

Redo the latest undone move.

Source code in src/patiencepilot/ui/tui.py
305
306
307
308
309
310
311
312
313
314
315
316
def action_redo(self) -> None:
    """Redo the latest undone move."""
    if self._is_real_world_mode:
        self._redo_known_move()
        return
    try:
        result = self.session.redo()
    except PatiencePilotError as error:
        self._set_status(str(error))
        return
    self._last_effects = result.effects
    self._set_status(f"Redid {move_to_id(result.move)}.")

action_new_game

action_new_game() -> None

Start a new game.

Source code in src/patiencepilot/ui/tui.py
318
319
320
321
322
323
324
325
326
327
def action_new_game(self) -> None:
    """Start a new game."""
    if self._is_real_world_mode:
        self._start_real_world_setup()
        self._last_effects = ()
        self._set_status("Started real-world setup.")
        return
    self._start_new_session()
    self._last_effects = ()
    self._set_status("Started a new game.")

action_save

action_save() -> None

Save the active session.

Source code in src/patiencepilot/ui/tui.py
329
330
331
332
333
334
335
336
337
338
339
340
341
342
def action_save(self) -> None:
    """Save the active session."""
    if self._is_real_world_mode:
        self._set_status("Saving real-world mirror sessions is not yet supported.")
        return
    if self.options.save_path is None:
        self._set_status("Start with --save PATH to enable saving.")
        return
    try:
        self._write_session(self.options.save_path)
    except OSError as error:
        self._set_status(str(error))
        return
    self._set_status(f"Saved to {self.options.save_path}.")

action_load

action_load() -> None

Load the configured session path.

Source code in src/patiencepilot/ui/tui.py
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
def action_load(self) -> None:
    """Load the configured session path."""
    if self._is_real_world_mode:
        self._set_status("Loading real-world mirror sessions is not yet supported.")
        return
    path = self.options.load_path or self.options.save_path
    if path is None:
        self._set_status("Start with --load PATH to enable loading.")
        return
    try:
        self.service.import_session(_read_json_object(path))
    except (OSError, json.JSONDecodeError, PatiencePilotError, ValueError) as error:
        self._set_status(str(error))
        return
    self._last_effects = ()
    self._set_status(f"Loaded {path}.")

build_parser

build_parser() -> argparse.ArgumentParser

Return the TUI argument parser.

Source code in src/patiencepilot/ui/tui.py
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
def build_parser() -> argparse.ArgumentParser:
    """Return the TUI argument parser."""
    parser = argparse.ArgumentParser(prog="patiencepilot-tui", description="Play Klondike in a Textual TUI.")
    parser.add_argument("--version", action="version", version=f"patiencepilot-tui {__version__}")
    parser.add_argument("--seed", metavar="VALUE", help="Seed for a reproducible deal.")
    parser.add_argument("--draw-count", type=int, default=1, metavar="N", help="Klondike draw count.")
    parser.add_argument("--redeals", metavar="N|none", help="Klondike redeal limit, or none for unlimited redeals.")
    parser.add_argument("--load", type=Path, metavar="PATH", help="Load a saved session JSON payload.")
    parser.add_argument("--save", type=Path, metavar="PATH", help="Save the session JSON payload from the TUI.")
    parser.add_argument("--solver", default="dummy", metavar="NAME", help="Registered solver name or alias.")
    parser.add_argument("--advice-time-limit", type=float, metavar="SECONDS", help="Optional solver time limit.")
    parser.add_argument("--advice-node-limit", type=int, metavar="NODES", help="Optional solver node limit.")
    parser.add_argument(
        "--advice-depth-limit",
        type=int,
        default=1,
        metavar="DEPTH",
        help="Optional solver depth limit. Defaults to 1 for quick interactive advice.",
    )
    parser.add_argument(
        "--real-world",
        action="store_true",
        help="Mirror a physical Klondike game with guided visible-card entry.",
    )
    return parser

main

main(argv: Sequence[str] | None = None) -> int

Run the TUI.

Source code in src/patiencepilot/ui/tui.py
741
742
743
744
745
def main(argv: Sequence[str] | None = None) -> int:
    """Run the TUI."""
    options = options_from_args(build_parser().parse_args(argv))
    PatiencePilotTui(options).run()
    return 0

options_from_args

options_from_args(args: Namespace) -> TuiOptions

Return TUI options from parsed arguments.

Source code in src/patiencepilot/ui/tui.py
748
749
750
751
752
753
754
755
756
757
758
759
760
761
def options_from_args(args: argparse.Namespace) -> TuiOptions:
    """Return TUI options from parsed arguments."""
    return TuiOptions(
        seed=_parse_seed(args.seed),
        draw_count=args.draw_count,
        redeals=_parse_redeals(args.redeals),
        load_path=args.load,
        save_path=args.save,
        real_world=args.real_world,
        solver=args.solver,
        advice_time_limit=args.advice_time_limit,
        advice_node_limit=args.advice_node_limit,
        advice_depth_limit=args.advice_depth_limit,
    )

render_board

render_board(session: GameSession) -> str

Return a compact board rendering for the current session.

Source code in src/patiencepilot/ui/tui.py
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
def render_board(session: GameSession) -> str:
    """Return a compact board rendering for the current session."""
    state = session.state
    foundation_text = "  ".join(f"{suit.code}:{_top_or_dash(state.foundation(suit))}" for suit in SUIT_ORDER)
    redeals = "*" if state.redeals_allowed is None else str(state.redeals_allowed)
    stock_line = (
        f"Stock: {len(state.stock):>2}   Waste: {_top_or_dash(state.waste):<2}   "
        f"Redeals: {state.redeals_used}/{redeals}"
    )
    lines = [
        stock_line,
        f"Foundations: {foundation_text}",
        "",
        " ".join(f"T{index}".center(6) for index in range(len(state.tableau))),
    ]
    rows = tuple(_tableau_rows(state.tableau))
    lines.extend(" ".join(card.center(6) for card in row) for row in rows)
    return "\n".join(lines)

render_real_world_setup

render_real_world_setup(setup: RealWorldSetup) -> str

Return guided setup text for a real-world Klondike mirror.

Source code in src/patiencepilot/ui/tui.py
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
def render_real_world_setup(setup: RealWorldSetup) -> str:
    """Return guided setup text for a real-world Klondike mirror."""
    lines = [
        "Real-world mirror setup",
        "",
        "Enter the visible top card for each tableau column.",
        "Hidden cards are tracked as unknown positions.",
        "",
    ]
    for column in range(7):
        value = setup.tableau_cards[column].code if column < len(setup.tableau_cards) else "--"
        lines.append(f"T{column}: {'## ' * column}{value}")
    lines.append("")
    lines.append(f"Progress: {len(setup.tableau_cards)}/7 visible tableau cards")
    return "\n".join(lines)

render_player_view

render_player_view(view: PlayerView) -> str

Return a compact player-known board rendering.

Source code in src/patiencepilot/ui/tui.py
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
def render_player_view(view: PlayerView) -> str:
    """Return a compact player-known board rendering."""
    foundation_text = "  ".join(f"{suit.code}:{_top_or_dash(view.foundation(suit))}" for suit in SUIT_ORDER)
    redeals = "*" if view.redeals_allowed is None else str(view.redeals_allowed)
    stock_line = (
        f"Stock: {view.stock_count:>2}   Waste: {_top_or_dash(view.waste):<2}   Redeals: {view.redeals_used}/{redeals}"
    )
    lines = [
        "Real-world mirror",
        stock_line,
        f"Foundations: {foundation_text}",
        f"Unknown cards: {len(view.unknown.unseen_cards)}",
        "",
        " ".join(f"T{index}".center(6) for index in range(len(view.tableau))),
    ]
    rows = tuple(_player_tableau_rows(view.tableau))
    lines.extend(" ".join(card.center(6) for card in row) for row in rows)
    return "\n".join(lines)
render_known_legal_moves(view: PlayerView) -> str

Return player-visible legal moves formatted for display.

Source code in src/patiencepilot/ui/tui.py
821
822
823
824
825
826
827
828
829
def render_known_legal_moves(view: PlayerView) -> str:
    """Return player-visible legal moves formatted for display."""
    moves = visible_klondike_moves(view)
    if not moves:
        return "Legal moves\n\nNo legal moves."
    lines = ["Legal moves", ""]
    for index, move in enumerate(moves, start=1):
        lines.append(f"{index:>2}. {move_to_id(move)}")
    return "\n".join(lines)

render_known_history

render_known_history(session: KnownGameSession) -> str

Return recent move history for a real-world mirror session.

Source code in src/patiencepilot/ui/tui.py
832
833
834
835
836
837
def render_known_history(session: KnownGameSession) -> str:
    """Return recent move history for a real-world mirror session."""
    moves = session.move_history[-6:]
    if not moves:
        return "History\n\nNo moves yet."
    return "History\n\n" + "  ".join(move_to_id(move) for move in moves)
render_legal_moves(session: GameSession) -> str

Return legal moves formatted for display.

Source code in src/patiencepilot/ui/tui.py
840
841
842
843
844
845
846
847
848
def render_legal_moves(session: GameSession) -> str:
    """Return legal moves formatted for display."""
    moves = session.legal_moves()
    if not moves:
        return "Legal moves\n\nNo legal moves."
    lines = ["Legal moves", ""]
    for index, move in enumerate(moves, start=1):
        lines.append(f"{index:>2}. {move_to_id(move)}")
    return "\n".join(lines)

render_history

render_history(session: GameSession) -> str

Return recent move history.

Source code in src/patiencepilot/ui/tui.py
851
852
853
854
855
856
def render_history(session: GameSession) -> str:
    """Return recent move history."""
    moves = session.move_history[-6:]
    if not moves:
        return "History\n\nNo moves yet."
    return "History\n\n" + "  ".join(move_to_id(move) for move in moves)

render_status

render_status(
    status: str, effects: tuple[MoveEffect, ...]
) -> str

Return status and latest effects text.

Source code in src/patiencepilot/ui/tui.py
859
860
861
862
863
def render_status(status: str, effects: tuple[MoveEffect, ...]) -> str:
    """Return status and latest effects text."""
    if not effects:
        return status
    return status + "\n" + "\n".join(f"- {_format_effect(effect)}" for effect in effects)