​a_maze_ing /
render / interactive.py
159 commits
09-06-2026
493 lines 15 kB
  1"""Interactive single-keypress display loop for mazes."""
  2
  3import copy
  4import os
  5import select
  6import sys
  7import termios
  8import tty
  9from collections import deque
 10from collections.abc import Callable, Iterator
 11from typing import TypeVar
 12
 13from mazegen import MazeGenerator, MazegenError, Grid, Position
 14
 15from .pixels import render_maze
 16
 17from .render_types import (
 18    CLEAR,
 19    HOME,
 20    ALT_SCREEN_ON,
 21    ALT_SCREEN_OFF,
 22    GEN_DELAY,
 23    SOLVE_DELAY,
 24    SPEED_FACTORS,
 25    SPEED_DEFAULT,
 26    NUM_COLORS,
 27    FOOTER,
 28    FOOTER_PURE,
 29    THEME_NAMES,
 30)
 31
 32_Step = TypeVar("_Step")
 33_Snap = TypeVar("_Snap")
 34
 35_Anim = Callable[
 36    [MazeGenerator, int, int, bool, bool], tuple[str | None, int, int]
 37]
 38
 39_HISTORY = 10
 40
 41
 42def _kbhit(timeout: float | None) -> str | None:
 43    """Return next keypress if available within timeout seconds, else None.
 44
 45    A timeout of None blocks until a key arrives. Escape sequences (arrow
 46    keys, function keys, alt-modified keys, mouse, paste) are swallowed
 47    and reported as None so the caller treats them as no input rather
 48    than dispatching their trailing bytes as commands.
 49    """
 50    fd = sys.stdin.fileno()
 51    rlist, _, _ = select.select([fd], [], [], timeout)
 52    if not rlist:
 53        return None
 54    data = os.read(fd, 8).decode("utf-8", errors="ignore")
 55    if not data or data.startswith("\x1b"):
 56        return None
 57    return data[:1]
 58
 59
 60def _footer(
 61    gen: MazeGenerator,
 62    color_idx: int,
 63    speed_idx: int,
 64    pure_ascii: bool,
 65    randomize_endpoints: bool,
 66) -> str:
 67    """Build the multi-row footer with current config + theme status.
 68
 69    Pure-ASCII mode shows the same control help and status cells, minus
 70    the color-only 'theme' cell (the [C] key is likewise dropped from
 71    FOOTER_PURE), since color is disabled there.
 72    """
 73    cells = [
 74        ("algo", gen.algorithm),
 75        ("perfect", "yes" if gen.perfect else "no"),
 76        ("glyph", "on" if gen.glyph else "off"),
 77        ("endpoints", "random" if randomize_endpoints else "fixed"),
 78    ]
 79    if not pure_ascii:
 80        cells.append(("theme", THEME_NAMES[color_idx % len(THEME_NAMES)]))
 81    cells.append(("seed", str(gen.seed)))
 82    cells.append(("speed", f"{1 / SPEED_FACTORS[speed_idx]:g}x"))
 83    rendered = [f"{k}: {v}" for k, v in cells]
 84    cols = 3
 85    nrows = (len(rendered) + cols - 1) // cols
 86    col_widths = [
 87        max(
 88            (
 89                len(rendered[r * cols + c])
 90                for r in range(nrows)
 91                if r * cols + c < len(rendered)
 92            ),
 93            default=0,
 94        )
 95        for c in range(cols)
 96    ]
 97    gutter = "    "
 98    rows = []
 99    for r in range(nrows):
100        padded = [
101            rendered[r * cols + c].ljust(col_widths[c])
102            for c in range(cols)
103            if r * cols + c < len(rendered)
104        ]
105        rows.append("    " + gutter.join(padded).rstrip() + "\033[K")
106    header = FOOTER_PURE if pure_ascii else FOOTER
107    return f"{header}\n" + "\n".join(rows)
108
109
110def _draw_anim_frame(
111    gen: MazeGenerator,
112    color_idx: int,
113    speed_idx: int,
114    delay: float | None,
115    pure_ascii: bool,
116    randomize_endpoints: bool,
117    *,
118    path_steps: int | None = None,
119    visited_cells: set[Position] | None = None,
120    backtrack: set[Position] | None = None,
121) -> tuple[str | None, int]:
122    """Draw one animation frame and poll a single keypress.
123
124    'c' cycles wall color and is consumed. Any other key is returned.
125    A delay of None blocks until a key arrives (paused mode). speed_idx
126    only feeds the footer readout; the actual delay is computed upstream.
127
128    Returns:
129        Tuple of (interrupting key or None, updated color_idx).
130    """
131    footer = _footer(
132        gen, color_idx, speed_idx, pure_ascii, randomize_endpoints
133    )
134    sys.stdout.write(HOME)
135    sys.stdout.write(
136        render_maze(
137            gen,
138            color_idx=color_idx,
139            path_steps=path_steps,
140            visited_cells=visited_cells,
141            backtrack=backtrack,
142            footer=footer,
143            pure_ascii=pure_ascii,
144        )
145    )
146    sys.stdout.flush()
147    ch = _kbhit(delay)
148    if ch is not None and ch.lower() == "c":
149        return None, (color_idx + 1) % NUM_COLORS
150    return ch, color_idx
151
152
153def _run_animation(
154    source: Iterator[_Step],
155    snapshot_fn: Callable[[_Step], _Snap],
156    draw_fn: Callable[[_Snap, int, int, float | None], tuple[str | None, int]],
157    color_idx: int,
158    default_delay: float,
159    speed_idx: int,
160) -> tuple[str | None, int, int]:
161    """Play an animation with pause / rewind / step controls.
162
163    The loop maintains a bounded history (last _HISTORY frames) of
164    snapshots so the user can scrub backwards. Per tick it either
165    replays the next stored snapshot (after a rewind) or pulls a fresh
166    step from `source`, converts it via `snapshot_fn`, and renders it
167    via `draw_fn`. Snapshots must be independent of later mutations to
168    `source`'s underlying state.
169
170    Keys (interpreted from draw_fn's return value):
171        space: toggle pause.
172        ',': rewind one frame (capped at history depth) and pause.
173        '.': advance one frame and pause; pulls from source if at head.
174        '[': step the playback speed down one level (slower).
175        ']': step the playback speed up one level (faster).
176        any other: returned to caller as the interrupt key.
177
178    After interrupt or natural exhaustion, the remaining steps in
179    `source` are silently drained so any generator-side state ends in
180    its final value.
181
182    Returns:
183        Tuple of (interrupting key or None, final color_idx, final
184        speed_idx).
185    """
186    history: deque[_Snap] = deque(maxlen=_HISTORY)
187    cursor = -1
188    paused = False
189    interrupted: str | None = None
190    exhausted = False
191
192    def advance() -> bool:
193        nonlocal cursor, exhausted
194        if cursor < len(history) - 1:
195            cursor += 1
196            return True
197        if exhausted:
198            return False
199        try:
200            step = next(source)
201        except StopIteration:
202            exhausted = True
203            return False
204        history.append(snapshot_fn(step))
205        cursor = len(history) - 1
206        return True
207
208    if not advance():
209        return None, color_idx, speed_idx
210
211    while True:
212        snap = history[cursor]
213        delay: float | None = (
214            None if paused else default_delay * SPEED_FACTORS[speed_idx]
215        )
216        ch, color_idx = draw_fn(snap, color_idx, speed_idx, delay)
217
218        if ch == " ":
219            paused = not paused
220        elif ch == ",":
221            paused = True
222            cursor = max(0, cursor - 1)
223        elif ch == ".":
224            paused = True
225            advance()
226        elif ch == "[":
227            speed_idx = min(len(SPEED_FACTORS) - 1, speed_idx + 1)
228        elif ch == "]":
229            speed_idx = max(0, speed_idx - 1)
230        elif ch is not None:
231            interrupted = ch
232            break
233        elif paused:
234            continue
235        elif not advance():
236            break
237
238    for _ in source:
239        pass
240    return interrupted, color_idx, speed_idx
241
242
243def _animate_generate(
244    gen: MazeGenerator,
245    color_idx: int,
246    speed_idx: int,
247    pure_ascii: bool,
248    randomize_endpoints: bool,
249) -> tuple[str | None, int, int]:
250    """Animate carving of the current maze with its active algorithm.
251
252    Uses gen.algorithm (dfs or prim) via generate_steps. Replays
253    gen.seed so the same maze is rebuilt, not a new one. Each step pairs
254    the yielded grid with a snapshot of gen.backtrack, the dfs walk-back
255    corridor (empty during forward carving and throughout prim); the grid
256    is deep-copied into the rewind history while the cell set is copied
257    so it is independent of later mutation. The renderer swaps gen.grid
258    for the snapshot and highlights the corridor during draw.
259    """
260    _Frame = tuple[Grid, set[Position]]
261
262    def steps() -> Iterator[_Frame]:
263        for grid in gen.generate_steps(gen.seed):
264            yield grid, set(gen.backtrack)
265
266    def snapshot(frame: _Frame) -> _Frame:
267        grid, walkback = frame
268        return copy.deepcopy(grid), walkback
269
270    def draw(
271        snap: _Frame, ci: int, si: int, dly: float | None
272    ) -> tuple[str | None, int]:
273        grid, walkback = snap
274        saved = gen.grid
275        gen.grid = grid
276        try:
277            return _draw_anim_frame(
278                gen,
279                ci,
280                si,
281                dly,
282                pure_ascii,
283                randomize_endpoints,
284                backtrack=walkback,
285            )
286        finally:
287            gen.grid = saved
288
289    return _run_animation(
290        steps(),
291        snapshot,
292        draw,
293        color_idx,
294        GEN_DELAY,
295        speed_idx,
296    )
297
298
299def _animate_solve(
300    gen: MazeGenerator,
301    color_idx: int,
302    speed_idx: int,
303    pure_ascii: bool,
304    randomize_endpoints: bool,
305) -> tuple[str | None, int, int]:
306    """Animate BFS solve, highlighting each visited cell as it is reached."""
307    visited: set[Position] = set()
308
309    def steps() -> Iterator[frozenset[Position]]:
310        for pos in gen.solve_steps():
311            visited.add(pos)
312            yield frozenset(visited)
313
314    def draw(
315        snap: frozenset[Position], ci: int, si: int, dly: float | None
316    ) -> tuple[str | None, int]:
317        return _draw_anim_frame(
318            gen,
319            ci,
320            si,
321            dly,
322            pure_ascii,
323            randomize_endpoints,
324            visited_cells=set(snap),
325        )
326
327    return _run_animation(
328        steps(), lambda s: s, draw, color_idx, SOLVE_DELAY, speed_idx
329    )
330
331
332def _pick_random_endpoints(gen: MazeGenerator) -> tuple[Position, Position]:
333    """Pick two distinct valid cells outside the '42' glyph."""
334    pool = [
335        (x, y)
336        for y in range(gen.height)
337        for x in range(gen.width)
338        if (x, y) not in gen.pattern_cells
339    ]
340    a, b = gen._rng.sample(pool, 2)
341    return a, b
342
343
344def run_interactive(
345    gen: MazeGenerator,
346    pure_ascii: bool = False,
347    randomize_endpoints: bool = False,
348) -> None:
349    """Run the interactive display loop.
350
351    Displays the maze and responds to single-keypress commands.
352    Falls back to a one-shot print when stdin is not a TTY.
353
354    Keys:
355        r: Regenerate with a new random seed.
356        g: Animate maze generation (carving with the active algorithm).
357        s: Animate BFS solve (visited cells highlighted).
358        p: Toggle path display instantly.
359        c: Cycle wall color (disabled in pure-ASCII mode).
360        space: Pause / unpause an animation.
361        ',': Rewind one frame (up to 10) and pause.
362        '.': Step forward one frame and pause.
363        '[': Slow the animation down one speed level (persists).
364        ']': Speed the animation up one speed level (persists).
365        t: Toggle carving algorithm (dfs / prim) and regenerate.
366        b: Toggle perfect vs braided maze and regenerate.
367        y: Toggle '42' glyph embed and regenerate.
368        e: Toggle whether 'r' reshuffles entry/exit cells.
369        q / Ctrl-C: Quit.
370
371    Args:
372        gen: Initially generated and solved MazeGenerator.
373        pure_ascii: Force plain ASCII with no color (no truecolor blocks).
374        randomize_endpoints: When True, each regeneration ('r') also
375            picks fresh random entry/exit cells outside the glyph.
376    """
377    if not sys.stdin.isatty() or not sys.stdout.isatty():
378        if pure_ascii:
379            sys.stdout.write(
380                render_maze(gen, footer=FOOTER_PURE, pure_ascii=True)
381            )
382        return
383
384    show_path = False
385    color_idx = 0
386    speed_idx = SPEED_DEFAULT
387    pending: str | None = None
388
389    fd = sys.stdin.fileno()
390    old = termios.tcgetattr(fd)
391
392    def draw() -> None:
393        """Clear screen and redraw maze."""
394        sys.stdout.write(CLEAR)
395        footer = _footer(
396            gen, color_idx, speed_idx, pure_ascii, randomize_endpoints
397        )
398        sys.stdout.write(
399            render_maze(
400                gen,
401                show_path=show_path,
402                color_idx=color_idx,
403                footer=footer,
404                pure_ascii=pure_ascii,
405            )
406        )
407        sys.stdout.flush()
408
409    def run_anim(fn: _Anim, *, show: bool, solve_after: bool) -> None:
410        """Run an animation, redraw, requeue any interrupting key."""
411        nonlocal color_idx, speed_idx, show_path, pending
412        interrupted, color_idx, speed_idx = fn(
413            gen, color_idx, speed_idx, pure_ascii, randomize_endpoints
414        )
415        if solve_after:
416            gen.solve()
417        show_path = show
418        draw()
419        if interrupted:
420            pending = interrupted
421
422    def regen() -> None:
423        """Regenerate maze + solve + reset path display."""
424        nonlocal show_path
425        if randomize_endpoints:
426            gen.entry, gen.exit_ = _pick_random_endpoints(gen)
427        gen.generate()
428        gen.solve()
429        show_path = False
430        draw()
431
432    try:
433        tty.setcbreak(fd)
434        sys.stdout.write(ALT_SCREEN_ON)
435        draw()
436        while True:
437            if pending is not None:
438                ch = pending
439                pending = None
440            else:
441                data = os.read(fd, 8).decode("utf-8", errors="ignore")
442                if not data or data == "\x04":
443                    break
444                if data.startswith("\x1b"):
445                    continue
446                ch = data[:1]
447            ch = ch.lower()
448
449            if ch == "q":
450                break
451            if ch == "r":
452                regen()
453            elif ch == "g":
454                run_anim(_animate_generate, show=False, solve_after=True)
455            elif ch == "s":
456                run_anim(_animate_solve, show=True, solve_after=False)
457            elif ch == "p":
458                show_path = not show_path
459                draw()
460            elif ch == "c":
461                color_idx = (color_idx + 1) % NUM_COLORS
462                draw()
463            elif ch == "t":
464                gen.algorithm = "prim" if gen.algorithm == "dfs" else "dfs"
465                regen()
466            elif ch == "b":
467                gen.perfect = not gen.perfect
468                if not gen.perfect and gen.braid == 0.0:
469                    gen.braid = 0.5
470                regen()
471            elif ch == "y":
472                old_glyph = gen.glyph
473                gen.glyph = not gen.glyph
474                try:
475                    regen()
476                except MazegenError:
477                    gen.glyph = old_glyph
478                    regen()
479            elif ch == "e":
480                randomize_endpoints = not randomize_endpoints
481                draw()
482            elif ch == "[":
483                speed_idx = min(len(SPEED_FACTORS) - 1, speed_idx + 1)
484                draw()
485            elif ch == "]":
486                speed_idx = max(0, speed_idx - 1)
487                draw()
488    except KeyboardInterrupt:
489        pass
490    finally:
491        sys.stdout.write(ALT_SCREEN_OFF)
492        sys.stdout.flush()
493        termios.tcsetattr(fd, termios.TCSADRAIN, old)