readme
This project has been created as part of the 42 curriculum by mleitao, ohaponiu.
A-maze-ing is a maze generator and solver. It reads a configuration file, generates a rectangular maze whose walls are encoded as hex bit masks, writes the maze to an output file, and renders it in the terminal with an interactive view.
Every maze embeds a "42" glyph drawn in fully-closed cells, supports perfect (single-solution) and non-perfect (looping) topologies, and is fully reproducible from a seed.
The project is split in two:
mazegen/- a reusable, pip-installable package exposing a single public class,MazeGenerator. All generation and solving logic lives here. Seemazegen/README.mdfor its standalone documentation.- CLI application -
a_maze_ing.pyplusconfig.pyandrender/, wrapping the package into a runnable program.
Everything runs through the Makefile, which manages a local virtualenv (.venv).
| Command | Description |
|---|---|
make install | Installs dependencies to a venv |
make run | Same as make install and runs the program |
make debug | Starts up the debugger |
make build | Build MazeGen wheel |
make clean | Clean cache and other temporary files |
make fclean | Same as make clean and also removes venv |
make lint | Runs linter and type checker |
make lint-strict | Same as make lint but in strict mode |
make test | Runs the pytest suite |
Run directly:
python3 a_maze_ing.py config.txt
The program takes a single positional argument: the config file path. Errors go to stderr with a non-zero exit code (0 == success, 1 == unexpected error, 2 == config error).
After the first render, the terminal enters a single-keypress loop:
| Key | Action |
|---|---|
R | regenerate with a new random seed |
G | animate generation |
S | animate solving |
P | toggle path display |
C | cycle themes |
Q / Ctrl-C | quit |
Animations can be controlled with the following keys:
| Key | Action |
|---|---|
SPACE | pause animations |
, | pause and go back 1 step (max steps back = 10) |
. | pause and go forward 1 step |
[ | slow the animation down one speed level (persists) |
] | speed the animation up one speed level (persists) |
Configuration can be changed at runtime with the following keys:
| Key | Action |
|---|---|
T | cycle algorithms |
B | cycle perfect, imperfect |
Y | add/remove 42 glypth |
E | randomize/fix entry-exit endpoints |
KEY=VALUE, one per line. # starts a comment; blank lines are ignored.
| Key | Type | Example |
|---|---|---|
WIDTH | int ≥ 2 | WIDTH=20 |
HEIGHT | int ≥ 2 | HEIGHT=20 |
ENTRY | x,y | ENTRY=0,0 |
EXIT | x,y | EXIT=19,19 |
OUTPUT_FILE | path | OUTPUT_FILE=maze.txt |
PERFECT | True/False | PERFECT=False |
| Key | Default | Values |
|---|---|---|
SEED | random | int |
ALGORITHM | dfs | dfs, prim (case-insensitive) |
PURE_ASCII | False | True/False |
GLYPH | True | True/False |
BRAID | 0.0 | float in [0.0, 1.0] |
RANDOMIZE_ENDPOINTS | False | True/False |
CLAMP_ENDPOINTS | False | True/False |
PERFECT=True produces a spanning tree (exactly one path between any two cells). PERFECT=False keeps the same spanning tree and then runs a braiding pass: a fraction BRAID of dead-ends is sampled and each gets an extra wall opened, introducing loops. BRAID=0.0 leaves the maze perfect even when PERFECT=False; BRAID=1.0 removes every eligible dead-end. The braid pass refuses any opening that would create a 3×3 open block. BRAID is ignored when PERFECT=True.
PURE_ASCII=True renders box-drawing ASCII instead of colored truecolor blocks (space cells with a 24-bit background color; no Unicode block glyphs are used).
RANDOMIZE_ENDPOINTS=True picks fresh random entry/exit cells (outside the glyph) on every regeneration in the interactive view; False keeps the configured endpoints.
CLAMP_ENDPOINTS=True silently substitutes out-of-bounds ENTRY coords with (0, 0) and out-of-bounds EXIT coords with (WIDTH-1, HEIGHT-1) per axis, instead of raising.
The parser rejects, with a clear message and exit code 2: unreadable files, malformed lines, missing/duplicate/unknown keys, out-of-bounds or equal entry/exit. The generator separately rejects, also with exit code 2, mazes too small to fit the "42" glyph (minimum 9×7, when GLYPH=True which is the default) and entries/exits that land on a glyph cell. Set GLYPH=False to skip the pattern and remove both restrictions.
# mandatory keys
WIDTH=20
HEIGHT=20
ENTRY=0,0
EXIT=19,19
OUTPUT_FILE=maze.txt
PERFECT=False
# optional keys
ALGORITHM=prim
PURE_ASCII=False
SEED=42
GLYPH=True
# Only matters on perfect=false
# 1.0 = remove all dead ends, 0.0 = don't remove any (equivalent to perfect=true)
BRAID=0.9
# Randomize entry/exit on maze regeneration
RANDOMIZE_ENDPOINTS=False
# Clamp entry/exit if they are out of bounds (not needed on randomized endpoints)
CLAMP_ENDPOINTS=True
<row0 hex>
...
<rowH-1 hex>
<entry_x>,<entry_y>
<exit_x>,<exit_y>
<path string>
Each row is uppercase hex, one digit per cell, where each digit encodes the closed walls (N=1, E=2, S=4, W=8; a set bit means the wall is closed). The path is a string over {N, E, S, W}. The output_validator.py shipped with the subject (not part of this repository) checks the neighbour-bit coherence of this file:
python3 output_validator.py maze.txt # empty output == valid
The bundled config.txt selects Prim's algorithm (the parser falls back to dfs when ALGORITHM is omitted). Prim grows the maze from the entry by repeatedly carving a random frontier edge, giving a bushy texture with many short branches. Reserved "42" cells are excluded from the frontier.
DFS (the iterative recursive-backtracker) is available via ALGORITHM=dfs. It uses an explicit stack to avoid Python's recursion limit and produces long winding corridors. Both algorithms produce a spanning tree and honor PERFECT.
Solving uses BFS. The graph is unweighted, so breadth-first search yields a shortest entry → exit path in O(W×H) with no priority queue, and returns a deterministic path given a fixed neighbour iteration order. When a non-perfect maze offers several routes, BFS returns the shortest.
mazegen exposes exactly one public class, MazeGenerator:
from mazegen import MazeGenerator, MazegenError
gen = MazeGenerator(
width=20,
height=20,
entry=(0, 0),
exit_=(19, 19),
perfect=False,
algorithm="prim", # optional; "prim" (default) or "dfs"
glyph=True, # optional; embed the centred "42" pattern
braid=0.5, # optional; dead-end removal fraction when perfect=False
)
gen.generate(42) # pass a seed for reproducibility; omit for random
gen.solve()
gen.grid # list[list[int]] — wall bits per cell
gen.path # "EES..." — shortest path as NESW string
gen.seed # seed used by the last generate()
list(gen.to_hex_lines()) # one uppercase hex row per cell row
list(gen.to_output_lines()) # full spec output: hex rows, blank, entry, exit, path
MazeGenerator.pattern_cells_for(width, height) is a static method so callers can validate entry/exit against the reserved "42" glyph before constructing the generator. For animation, drive generate_steps() and solve_steps() directly—both yield after every step. During DFS carving, gen.backtrack holds the cells of the current walk-back corridor (empty while moving forward and throughout Prim) so a renderer can highlight backtracking.
Install the package on its own from the committed wheel:
pip install mazegen-1.0.0-py3-none-any.whl
- Wikipedia, Maze generation algorithm – concise summary of randomized DFS, randomized Prim's, and properties of spanning trees.
- Wikipedia, Breadth-first search – used for the unweighted shortest-path solver.
- VT100 / ANSI escape codes reference – alternate screen buffer, cursor control, and 24-bit truecolor sequences used by the renderer.
- Python docs:
termios,tty,select– single-keypress input handling. - PEP 257 – Docstring Conventions and the Google Python Style Guide – docstring style.
LLMs were used for:
- Polishing this README
- Understanding overall maze generation algorithms
- Understanding how to draw to the terminal
Both of the contributors worked on every part of the project; the focus split was:
- mleitao – mostly interactive terminal renderer (ASCII and truecolor), Prim's algorithm, documentation, and DRY refactors.
- ohaponiu – mostly initial
mazegenpackage, braiding, config options/validation, and later themes and extra config options.
1*This project has been created as part of the 42 curriculum by mleitao, ohaponiu.*
2
3# Description
4
5**A-maze-ing** is a maze generator and solver. It reads a configuration file, generates a rectangular maze whose walls are encoded as hex bit masks, writes the maze to an output file, and renders it in the terminal with an interactive view.
6
7Every maze embeds a "42" glyph drawn in fully-closed cells, supports perfect (single-solution) and non-perfect (looping) topologies, and is fully reproducible from a seed.
8
9The project is split in two:
10
11- **`mazegen/`** - a reusable, pip-installable package exposing a single public class, `MazeGenerator`. All generation and solving logic lives here. See [`mazegen/README.md`](mazegen/README.md) for its standalone documentation.
12- **CLI application** - `a_maze_ing.py` plus `config.py` and `render/`, wrapping the package into a runnable program.
13
14# Instructions
15
16Everything runs through the `Makefile`, which manages a local virtualenv (`.venv`).
17
18## Makefile
19
20Command | Description
21--|--
22`make install` | Installs dependencies to a venv
23`make run` | Same as `make install` and runs the program
24`make debug` | Starts up the debugger
25`make build` | Build `MazeGen` wheel
26`make clean` | Clean cache and other temporary files
27`make fclean` | Same as `make clean` and also removes venv
28`make lint` | Runs linter and type checker
29`make lint-strict` | Same as `make lint` but in strict mode
30`make test` | Runs the pytest suite
31
32
33Run directly:
34
35```sh
36python3 a_maze_ing.py config.txt
37```
38
39The program takes a single positional argument: the `config` file path. Errors go to `stderr` with a non-zero exit code (`0` == success, `1` == unexpected error, `2` == `config` error).
40
41## Interactive controls
42
43After the first render, the terminal enters a single-keypress loop:
44
45| Key | Action |
46|-----|--------|
47| `R` | regenerate with a new random seed |
48| `G` | animate generation |
49| `S` | animate solving |
50| `P` | toggle path display |
51| `C` | cycle themes |
52| `Q` / Ctrl-C | quit |
53
54Animations can be controlled with the following keys:
55
56| Key | Action |
57|----|----|
58| `SPACE` | pause animations |
59| `,` | pause and go back 1 step (max steps back = 10) |
60| `.` | pause and go forward 1 step |
61| `[` | slow the animation down one speed level (persists) |
62| `]` | speed the animation up one speed level (persists) |
63
64
65Configuration can be changed at runtime with the following keys:
66
67| Key | Action |
68|----|----|
69| `T` | cycle algorithms |
70| `B` | cycle perfect, imperfect |
71| `Y` | add/remove 42 glypth |
72| `E` | randomize/fix entry-exit endpoints |
73
74
75## Config file format
76
77`KEY=VALUE`, one per line. `#` starts a comment; blank lines are ignored.
78
79### Mandatory keys
80
81| Key | Type | Example |
82|-----|------|---------|
83| `WIDTH` | int ≥ 2 | `WIDTH=20` |
84| `HEIGHT` | int ≥ 2 | `HEIGHT=20` |
85| `ENTRY` | `x,y` | `ENTRY=0,0` |
86| `EXIT` | `x,y` | `EXIT=19,19` |
87| `OUTPUT_FILE` | path | `OUTPUT_FILE=maze.txt` |
88| `PERFECT` | `True`/`False` | `PERFECT=False` |
89
90### Optional keys
91
92| Key | Default | Values |
93|-----|---------|--------|
94| `SEED` | random | int |
95| `ALGORITHM` | `dfs` | `dfs`, `prim` (case-insensitive) |
96| `PURE_ASCII` | `False` | `True`/`False` |
97| `GLYPH` | `True` | `True`/`False` |
98| `BRAID` | `0.0` | float in `[0.0, 1.0]` |
99| `RANDOMIZE_ENDPOINTS` | `False` | `True`/`False` |
100| `CLAMP_ENDPOINTS` | `False` | `True`/`False` |
101
102`PERFECT=True` produces a spanning tree (exactly one path between any two cells). `PERFECT=False` keeps the same spanning tree and then runs a braiding pass: a fraction `BRAID` of dead-ends is sampled and each gets an extra wall opened, introducing loops. `BRAID=0.0` leaves the maze perfect even when `PERFECT=False`; `BRAID=1.0` removes every eligible dead-end. The braid pass refuses any opening that would create a 3×3 open block. `BRAID` is ignored when `PERFECT=True`.
103
104`PURE_ASCII=True` renders box-drawing ASCII instead of colored truecolor blocks (space cells with a 24-bit background color; no Unicode block glyphs are used).
105
106`RANDOMIZE_ENDPOINTS=True` picks fresh random entry/exit cells (outside the glyph) on every regeneration in the interactive view; `False` keeps the configured endpoints.
107
108`CLAMP_ENDPOINTS=True` silently substitutes out-of-bounds `ENTRY` coords with `(0, 0)` and out-of-bounds `EXIT` coords with `(WIDTH-1, HEIGHT-1)` per axis, instead of raising.
109
110### Validation
111
112The parser rejects, with a clear message and exit code 2: unreadable files, malformed lines, missing/duplicate/unknown keys, out-of-bounds or equal entry/exit. The generator separately rejects, also with exit code 2, mazes too small to fit the "42" glyph (minimum **9×7**, when `GLYPH=True` which is the default) and entries/exits that land on a glyph cell. Set `GLYPH=False` to skip the pattern and remove both restrictions.
113
114### Default `config.txt`
115
116```
117# mandatory keys
118WIDTH=20
119HEIGHT=20
120ENTRY=0,0
121EXIT=19,19
122OUTPUT_FILE=maze.txt
123PERFECT=False
124
125# optional keys
126ALGORITHM=prim
127PURE_ASCII=False
128SEED=42
129GLYPH=True
130# Only matters on perfect=false
131# 1.0 = remove all dead ends, 0.0 = don't remove any (equivalent to perfect=true)
132BRAID=0.9
133# Randomize entry/exit on maze regeneration
134RANDOMIZE_ENDPOINTS=False
135# Clamp entry/exit if they are out of bounds (not needed on randomized endpoints)
136CLAMP_ENDPOINTS=True
137```
138
139## Output file format
140
141```
142<row0 hex>
143...
144<rowH-1 hex>
145
146<entry_x>,<entry_y>
147<exit_x>,<exit_y>
148<path string>
149```
150
151Each row is uppercase hex, one digit per cell, where each digit encodes the closed walls (`N=1, E=2, S=4, W=8`; a set bit means the wall is closed). The path is a string over `{N, E, S, W}`. The `output_validator.py` shipped with the subject (not part of this repository) checks the neighbour-bit coherence of this file:
152
153```sh
154python3 output_validator.py maze.txt # empty output == valid
155```
156
157## Algorithm choice
158
159**The bundled `config.txt` selects Prim's algorithm** (the parser falls back to `dfs` when `ALGORITHM` is omitted). Prim grows the maze from the entry by repeatedly carving a random frontier edge, giving a bushy texture with many short branches. Reserved "42" cells are excluded from the frontier.
160
161**DFS** (the iterative recursive-backtracker) is available via `ALGORITHM=dfs`. It uses an explicit stack to avoid Python's recursion limit and produces long winding corridors. Both algorithms produce a spanning tree and honor `PERFECT`.
162
163**Solving uses BFS.** The graph is unweighted, so breadth-first search yields a shortest entry → exit path in O(W×H) with no priority queue, and returns a deterministic path given a fixed neighbour iteration order. When a non-perfect maze offers several routes, BFS returns the shortest.
164
165## Reusable module
166
167`mazegen` exposes exactly one public class, `MazeGenerator`:
168
169```python
170from mazegen import MazeGenerator, MazegenError
171
172gen = MazeGenerator(
173 width=20,
174 height=20,
175 entry=(0, 0),
176 exit_=(19, 19),
177 perfect=False,
178 algorithm="prim", # optional; "prim" (default) or "dfs"
179 glyph=True, # optional; embed the centred "42" pattern
180 braid=0.5, # optional; dead-end removal fraction when perfect=False
181)
182gen.generate(42) # pass a seed for reproducibility; omit for random
183gen.solve()
184
185gen.grid # list[list[int]] — wall bits per cell
186gen.path # "EES..." — shortest path as NESW string
187gen.seed # seed used by the last generate()
188list(gen.to_hex_lines()) # one uppercase hex row per cell row
189list(gen.to_output_lines()) # full spec output: hex rows, blank, entry, exit, path
190```
191
192`MazeGenerator.pattern_cells_for(width, height)` is a static method so callers can validate entry/exit against the reserved "42" glyph before constructing the generator. For animation, drive `generate_steps()` and `solve_steps()` directly—both yield after every step. During DFS carving, `gen.backtrack` holds the cells of the current walk-back corridor (empty while moving forward and throughout Prim) so a renderer can highlight backtracking.
193
194Install the package on its own from the committed wheel:
195
196```sh
197pip install mazegen-1.0.0-py3-none-any.whl
198```
199
200## Resources
201
202- Wikipedia, [*Maze generation algorithm*](https://en.wikipedia.org/wiki/Maze_generation_algorithm) – concise summary of randomized DFS, randomized Prim's, and properties of spanning trees.
203- Wikipedia, [*Breadth-first search*](https://en.wikipedia.org/wiki/Breadth-first_search) – used for the unweighted shortest-path solver.
204- [VT100 / ANSI escape codes reference](https://en.wikipedia.org/wiki/ANSI_escape_code) – alternate screen buffer, cursor control, and 24-bit truecolor sequences used by the renderer.
205- Python docs: [`termios`](https://docs.python.org/3/library/termios.html), [`tty`](https://docs.python.org/3/library/tty.html), [`select`](https://docs.python.org/3/library/select.html) – single-keypress input handling.
206- [PEP 257 – Docstring Conventions](https://peps.python.org/pep-0257/) and the [Google Python Style Guide](https://google.github.io/styleguide/pyguide.html#383-functions-and-methods) – docstring style.
207
208### AI usage
209
210LLMs were used for:
211- Polishing this README
212- Understanding overall maze generation algorithms
213- Understanding how to draw to the terminal
214
215## Contributors
216
217Both of the contributors worked on every part of the project; the focus split was:
218
219- **mleitao** – mostly interactive terminal renderer (ASCII and truecolor), Prim's algorithm, documentation, and DRY refactors.
220- **ohaponiu** – mostly initial `mazegen` package, braiding, config options/validation, and later themes and extra config options.