​a_maze_ing /
render / pixels.py
159 commits
08-06-2026
264 lines 8.4 kB
  1"""Terminal renderer for MazeGenerator grids."""
  2
  3from mazegen import MazeGenerator, Grid, Position, DIR_CHAR, DX, DY, N, W
  4
  5from .render_types import (
  6    BG,
  7    PLAIN,
  8    RESET,
  9    PIXEL,
 10)
 11
 12_STEP: dict[str, tuple[int, int]] = {
 13    c: (DX[b], DY[b]) for b, c in DIR_CHAR.items()
 14}
 15
 16_WALL = "wall"
 17_GLYPH = "glyph"
 18_PATH = "path"
 19_VISITED = "visited"
 20_BACKTRACK = "backtrack"
 21_BG = "bg"
 22_CELL = "cell"
 23
 24_CORNER = "corner"
 25_VEDGE = "vedge"
 26_HEDGE = "hedge"
 27
 28_BLOCK_GLYPHS: dict[tuple[str, str], str] = {
 29    (_BG, _CORNER): PIXEL,
 30    (_BG, _VEDGE): PIXEL,
 31    (_BG, _HEDGE): PIXEL,
 32}
 33_ASCII_GLYPHS: dict[tuple[str, str], str] = {
 34    (_WALL, _CORNER): "+",
 35    (_WALL, _VEDGE): "|",
 36    (_WALL, _HEDGE): "--",
 37    (_GLYPH, _CORNER): "#",
 38    (_GLYPH, _VEDGE): "#",
 39    (_GLYPH, _HEDGE): "##",
 40    (_PATH, _VEDGE): ".",
 41    (_PATH, _HEDGE): "..",
 42    (_VISITED, _VEDGE): "~",
 43    (_VISITED, _HEDGE): "~~",
 44    (_BACKTRACK, _VEDGE): ":",
 45    (_BACKTRACK, _HEDGE): "::",
 46    (_BG, _CORNER): " ",
 47    (_BG, _VEDGE): " ",
 48    (_BG, _HEDGE): "  ",
 49}
 50
 51
 52def _cell_to_pixel(x: int, y: int) -> tuple[int, int]:
 53    """Return the pixel-grid coords of cell (x, y)'s center."""
 54    return (2 * x + 1, 2 * y + 1)
 55
 56
 57def _build_wall_mask(
 58    cols: int, rows: int, grid: Grid, pattern: set[Position]
 59) -> list[list[bool]]:
 60    """Precompute is-wall for every pixel-grid coord.
 61
 62    Pixel grid is (2*cols+1) wide by (2*rows+1) tall. Parity:
 63    even/even = corner, even/odd = vertical edge (W bit),
 64    odd/even = horizontal edge (N bit), odd/odd = cell body.
 65    Edges shared by two pattern cells are suppressed so the glyph
 66    renders as a connected shape rather than isolated bordered tiles.
 67    """
 68    pcols = cols * 2 + 1
 69    prows = rows * 2 + 1
 70    mask = [[False] * pcols for _ in range(prows)]
 71
 72    for px in range(pcols):
 73        mask[0][px] = True
 74        mask[prows - 1][px] = True
 75    for py in range(prows):
 76        mask[py][0] = True
 77        mask[py][pcols - 1] = True
 78
 79    for cy in range(rows):
 80        py = 2 * cy + 1
 81        for cx in range(1, cols):
 82            if (cx - 1, cy) in pattern and (cx, cy) in pattern:
 83                continue
 84            mask[py][2 * cx] = bool(grid[cy][cx] & W)
 85
 86    for cx in range(cols):
 87        px = 2 * cx + 1
 88        for cy in range(1, rows):
 89            if (cx, cy - 1) in pattern and (cx, cy) in pattern:
 90                continue
 91            mask[2 * cy][px] = bool(grid[cy][cx] & N)
 92
 93    for py in range(2, prows - 1, 2):
 94        for px in range(2, pcols - 1, 2):
 95            mask[py][px] = (
 96                mask[py - 1][px]
 97                or mask[py + 1][px]
 98                or mask[py][px - 1]
 99                or mask[py][px + 1]
100            )
101
102    return mask
103
104
105def _path_pixels(
106    gen: MazeGenerator, limit: int | None = None
107) -> set[tuple[int, int]]:
108    """Return pixel-grid coords of path cells and passages up to limit."""
109    pixels: set[tuple[int, int]] = set()
110    x, y = gen.entry
111    pixels.add(_cell_to_pixel(x, y))
112    steps = gen.path if limit is None else gen.path[:limit]
113    for d in steps:
114        dx, dy = _STEP[d]
115        px, py = _cell_to_pixel(x, y)
116        pixels.add((px + dx, py + dy))
117        x, y = x + dx, y + dy
118        pixels.add(_cell_to_pixel(x, y))
119    return pixels
120
121
122def _parity(px: int, py: int) -> str:
123    """Return the parity label for pixel-grid coord (px, py)."""
124    if px % 2 == 0 and py % 2 == 0:
125        return _CORNER
126    if px % 2 == 0:
127        return _VEDGE
128    if py % 2 == 0:
129        return _HEDGE
130    return _CELL
131
132
133def render_maze(
134    gen: MazeGenerator,
135    *,
136    show_path: bool = False,
137    color_idx: int = 0,
138    path_steps: int | None = None,
139    visited_cells: set[Position] | None = None,
140    backtrack: set[Position] | None = None,
141    footer: str = "",
142    pure_ascii: bool = False,
143) -> str:
144    """Render a maze as a terminal grid.
145
146    Each wall and cell occupies one 2-char-wide pixel. Output width is
147    2*(2*width+1) characters, approximately 122 chars for a 30-wide maze.
148
149    Args:
150        gen: Finished MazeGenerator (generate() already called).
151        show_path: Highlight the full solved path.
152        color_idx: Wall color palette index.
153        path_steps: Show only this many path steps; overrides show_path.
154        visited_cells: BFS-visited cell coords to highlight (animation).
155        backtrack: DFS walk-back corridor cells to highlight in the
156            backtrack color while the carver retreats (animation).
157        footer: Optional text appended below the maze grid.
158        pure_ascii: Render plain box-drawing ASCII glyphs with no ANSI
159            color codes. Safe to pipe to a file or non-color viewer.
160
161    Returns:
162        Multi-line string with a trailing newline.
163    """
164    colors = PLAIN if pure_ascii else BG
165    theme = color_idx % len(colors.palette)
166    entry_color = colors.entry[theme]
167    exit_color = colors.exit_[theme]
168    glyph_color = colors.dark[theme]
169    path_color = colors.path[theme]
170    visited_color = colors.visited[theme]
171    bg_color = colors.bg[theme]
172    backtrack_color = colors.backtrack[theme]
173    kind_color: dict[str, str] = {
174        _WALL: colors.palette[theme],
175        _GLYPH: glyph_color,
176        _PATH: path_color,
177        _VISITED: visited_color,
178        _BACKTRACK: backtrack_color,
179        _BG: bg_color,
180    }
181    reset = "" if pure_ascii else RESET
182    glyphs = _ASCII_GLYPHS if pure_ascii else _BLOCK_GLYPHS
183
184    if path_steps is not None:
185        path_px: set[tuple[int, int]] = _path_pixels(gen, path_steps)
186    elif show_path:
187        path_px = _path_pixels(gen)
188    else:
189        path_px = set()
190
191    cols = gen.width
192    rows = gen.height
193    grid = gen.grid
194    pattern = gen.pattern_cells
195    mask = _build_wall_mask(cols, rows, grid, pattern)
196
197    def _spans(s: set[Position], px: int, py: int) -> bool:
198        """True if pixel bridges adjacent cells that all belong to s.
199
200        Vertical edge: both flanking cells in s.
201        Horizontal edge: both flanking cells in s.
202        Corner: all four diagonal cells in s.
203        """
204        cx, cy = px // 2, py // 2
205        if px % 2 == 0 and py % 2 == 1:
206            return (cx - 1, cy) in s and (cx, cy) in s
207        if px % 2 == 1 and py % 2 == 0:
208            return (cx, cy - 1) in s and (cx, cy) in s
209        return all((cx + ox, cy + oy) in s for ox in (-1, 0) for oy in (-1, 0))
210
211    def _classify(px: int, py: int) -> str:
212        """Map pixel-grid coord to its render kind."""
213        if mask[py][px]:
214            return _WALL
215        if px % 2 == 1 and py % 2 == 1:
216            return _CELL
217        if (px, py) in path_px:
218            return _PATH
219        if _spans(pattern, px, py):
220            return _GLYPH
221        if backtrack is not None and _spans(backtrack, px, py):
222            return _BACKTRACK
223        if visited_cells is not None and _spans(visited_cells, px, py):
224            return _VISITED
225        return _BG
226
227    def _cell_marker(pos: Position) -> str:
228        """Return the colored 2-char glyph for cell pos."""
229
230        def _mark(color: str, ascii_glyph: str) -> str:
231            """Wrap a glyph in color; use PIXEL block unless pure_ascii."""
232            return color + (ascii_glyph if pure_ascii else PIXEL) + reset
233
234        px, py = _cell_to_pixel(*pos)
235        if pos in pattern:
236            return _mark(glyph_color, "##")
237        if pos == gen.entry:
238            return _mark(entry_color, "E ")
239        if pos == gen.exit_:
240            return _mark(exit_color, "X ")
241        if backtrack is not None and pos in backtrack:
242            return _mark(backtrack_color, "::")
243        if (px, py) in path_px:
244            return _mark(path_color, "..")
245        if visited_cells is not None and pos in visited_cells:
246            return _mark(visited_color, "~~")
247        return _mark(bg_color, "  ")
248
249    def _emit(px: int, py: int) -> str:
250        """Render one pixel-grid cell."""
251        kind = _classify(px, py)
252        if kind == _CELL:
253            return _cell_marker((px // 2, py // 2))
254        parity = _parity(px, py)
255        glyph = glyphs.get((kind, parity), glyphs[(_BG, parity)])
256        return kind_color[kind] + glyph + reset
257
258    lines: list[str] = [
259        "".join(_emit(px, py) for px in range(cols * 2 + 1))
260        for py in range(rows * 2 + 1)
261    ]
262
263    suffix = ("\n" + footer) if footer else ""
264    return "\n".join(lines) + "\n" + suffix + "\n"