(topics-interactive-game)=

# Test an interactive game

In *The Last Beacon*, the harbor is dark. Find the brass key at Lantern Quay,
go north, and light the beacon. The game uses only the standard library.
Run the commands from the repository root with `libvt` installed.

## Play the game

On a POSIX terminal, run the game to explore with the arrow keys. Type
`help` for commands and `quit` to leave.

```console
$ python examples/last_beacon/game.py
```

Use `--transcript` for line-by-line play on any platform. Enter `north`
and try to light the beacon without the key.

```python
>>> import subprocess
>>> import sys
>>> game = subprocess.run(
...     [sys.executable, "examples/last_beacon/game.py", "--transcript"],
...     input="north\nlight beacon\nquit\n",
...     text=True,
...     capture_output=True,
...     check=True,
... )
>>> "You need the brass key." in game.stdout
True
```

## Drive the game from a test

On POSIX, run the tour to play through a real pseudo-terminal.

```console
$ python examples/last_beacon/tour.py
```

The tour opens the child with {func}`~libvt.aio.open_pty`. It pastes
`take key`, submits it with Enter, and sends Up using the cursor-key mode
requested by the child. It waits for the room heading to confirm movement,
then resizes to 45 columns by 10 rows. The new size in the title comes from
the child's terminal, so it confirms the resize reached the application.

The tour checks the victory message for bold green text and keeps the arrival
{class}`~libvt.snapshot.Snapshot` to verify that it still shows the quay at
the original width. Capture the winning screen before quitting because the
child restores the primary screen as it exits.

```python
>>> import os
>>> import pathlib
>>> import subprocess
>>> import sys
>>> import tempfile
>>> if os.name == "posix":
...     with tempfile.TemporaryDirectory() as directory:
...         trace = pathlib.Path(directory) / "beacon.json"
...         tour = [sys.executable, "examples/last_beacon/tour.py"]
...         live = subprocess.check_output([*tour, "--record", str(trace)], timeout=30)
...         saved = subprocess.check_output([*tour, "--replay", str(trace)], timeout=30)
...         matched = b"The beacon is lit!" in live and live == saved
... else:  # doctest: +HIDE
...     matched = True  # doctest: +HIDE
>>> matched
True
```

## Replay the winning screen

The bundled recording stores output bytes and viewport sizes at each
checkpoint. Replay applies the sizes and feeds the bytes to a fresh
{class}`~libvt.terminal.Terminal`. Each checkpoint is compared with its
original {func}`~libvt.testing.serialize_vt_snapshot` output. Feeding one
byte at a time exercises escape sequences split across reads.

```console
$ python examples/last_beacon/tour.py --replay --chunk-size 1
```

```python
>>> import subprocess
>>> import sys
>>> replay = subprocess.run(
...     [sys.executable, "examples/last_beacon/tour.py", "--replay", "--chunk-size", "1"],
...     capture_output=True, encoding="utf-8", check=True,
... )
>>> replay.stdout.splitlines()[0]
'size=45x10 cursor=(9,2,vis=True) alt=True modes=[DECCKM,BRACKETED_PASTE]'
>>> "r8[0..18]: bold fg=green" in replay.stdout
True
```

Replay stops at the first checkpoint whose saved screen differs. The error
names the checkpoint. You can check a recording from an optimized interpreter
as well.

```python
>>> import json
>>> import pathlib
>>> import subprocess
>>> import sys
>>> import tempfile
>>> example = pathlib.Path("examples/last_beacon")
>>> frames = json.loads((example / "walkthrough.json").read_text(encoding="utf-8"))
>>> frames[1]["screen"] = frames[0]["screen"]
>>> with tempfile.TemporaryDirectory() as directory:
...     trace = pathlib.Path(directory) / "changed.json"
...     _ = trace.write_text(json.dumps(frames), encoding="utf-8")
...     result = subprocess.run(
...         [sys.executable, "-O", str(example / "tour.py"), "--replay", str(trace)],
...         capture_output=True, text=True, check=False,
...     )
>>> result.returncode, result.stderr.strip()
(1, "tour.py: Screen differs at checkpoint 'key'")
```

On POSIX, use `--record` to save a fresh run. The bounded
{class}`~libvt.recorder.FlightRecorder` supplies the bytes received from
the child. A fresh trace can include an intermediate redraw between paste
and Enter. The completed checkpoints still match. Replay runs on any
supported platform without starting the game.

```console
$ python examples/last_beacon/tour.py --record beacon.json
```

```console
$ python examples/last_beacon/tour.py --replay beacon.json
```
