-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patha_maze_ing.py
More file actions
executable file
·386 lines (327 loc) · 12.2 KB
/
Copy patha_maze_ing.py
File metadata and controls
executable file
·386 lines (327 loc) · 12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
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
"""A-Maze-ing CLI: parse a config file, generate the maze, write the
output file, then launch the MLX visualizer.
Usage::
python3 a_maze_ing.py config.txt
The config file is a plain ``KEY=VALUE`` document; ``#``-prefixed lines and
blank lines are ignored. Required keys are ``WIDTH``, ``HEIGHT``,
``ENTRY``, ``EXIT``, ``OUTPUT_FILE``, ``PERFECT``. Optional keys are
``SEED`` (RNG reproducibility) and ``IMPRATE`` (0-100, imperfection rate).
"""
from __future__ import annotations
import os
import sys
import time
from enum import IntEnum
from typing import Any, Optional, Tuple
from cffi import FFI
SCRIPT_DIR: str = os.path.dirname(os.path.abspath(__file__))
DEFAULT_LIB: str = os.path.join(SCRIPT_DIR, "libamazing.so")
DEFAULT_CONFIG: str = os.path.join(SCRIPT_DIR, "config.txt")
class Direction(IntEnum):
"""Maze wall direction; matches ``e_direction`` in ``mazegen.h``."""
NORTH = 0
EAST = 1
SOUTH = 2
WEST = 3
class KeyCodes(IntEnum):
"""X11 keysyms for the on-screen panel buttons (digits 1-4)."""
REGEN = 49
SOLVE = 50
RECOLOR = 51
QUIT = 52
_REQUIRED_KEYS: Tuple[str, ...] = (
"WIDTH", "HEIGHT", "ENTRY", "EXIT", "OUTPUT_FILE", "PERFECT",
)
_OPTIONAL_KEYS: Tuple[str, ...] = ("SEED", "IMPRATE")
_ALLOWED_KEYS: set[str] = set(_REQUIRED_KEYS) | set(_OPTIONAL_KEYS)
def _coerce(key: str, value: str, lineno: int, path: str) -> Any:
"""Convert a raw config value to its typed Python representation.
:raises ValueError: with file:line context if the value is malformed.
"""
try:
if key in ("WIDTH", "HEIGHT", "SEED", "IMPRATE"):
return int(value)
if key in ("ENTRY", "EXIT"):
parts: list[str] = value.split(",")
if len(parts) != 2:
raise ValueError("expected 'x,y'")
return (int(parts[0].strip()), int(parts[1].strip()))
if key == "PERFECT":
v: str = value.strip().lower()
if v in ("true", "1", "yes"):
return True
if v in ("false", "0", "no"):
return False
raise ValueError("expected true/false")
return value
except ValueError as e:
raise ValueError(
f"{path}:{lineno}: invalid value for {key}: {e}"
) from None
def _parse_config(path: str) -> dict[str, Any]:
"""Parse a ``KEY=VALUE`` config file into a typed dict.
Lines starting with ``#`` and blank lines are skipped. Inline trailing
``# comments`` are also stripped.
:param path: filesystem path to the config file.
:raises FileNotFoundError: if ``path`` does not exist.
:raises ValueError: on missing/extra keys, malformed lines, or
type-coercion failures.
"""
cfg: dict[str, Any] = {}
with open(path, "r", encoding="utf-8") as fp:
for lineno, raw in enumerate(fp, 1):
line: str = raw.split("#", 1)[0].strip()
if not line:
continue
if "=" not in line:
raise ValueError(
f"{path}:{lineno}: expected KEY=VALUE, got {raw!r}"
)
key_raw, value_raw = line.split("=", 1)
key: str = key_raw.strip().upper()
value: str = value_raw.strip()
if key not in _ALLOWED_KEYS:
raise ValueError(
f"{path}:{lineno}: unknown config key {key!r}"
)
cfg[key] = _coerce(key, value, lineno, path)
missing: list[str] = [k for k in _REQUIRED_KEYS if k not in cfg]
if missing:
raise ValueError(
f"{path}: missing required keys: {', '.join(missing)}"
)
w: int = int(cfg["WIDTH"])
h: int = int(cfg["HEIGHT"])
if w < 1 or h < 1:
raise ValueError(
f"WIDTH and HEIGHT must be >= 1; got {w}x{h}"
)
for label in ("ENTRY", "EXIT"):
x, y = cfg[label]
if not (0 <= x < w and 0 <= y < h):
raise ValueError(
f"{label}={x},{y} out of bounds for {w}x{h}"
)
if cfg["ENTRY"] == cfg["EXIT"]:
raise ValueError("ENTRY and EXIT must differ")
if cfg.get("IMPRATE") is not None:
r: int = int(cfg["IMPRATE"])
if r < 0 or r > 100:
raise ValueError(f"IMPRATE must be in [0, 100]; got {r}")
return cfg
class MazeGenerator:
"""Application orchestrator: load libamazing, drive maze + MLX loop."""
_CDEF: str = """
typedef struct s_img {
char *purpose;
void *img;
unsigned char *addr;
unsigned int bits_per_pixel;
unsigned int line_length;
unsigned int endian;
unsigned int width;
unsigned int height;
} t_img;
typedef struct s_cell {
struct s_cell *parent;
int *options;
int visited;
int wall;
int patterned;
int x;
int y;
} t_cell;
typedef struct s_maze {
int width;
int height;
int entry_x;
int entry_y;
int exit_x;
int exit_y;
char *output_filename;
bool is_solved;
bool is_perfect;
t_cell **grid;
int imprate;
} t_maze;
typedef struct s_mlx {
void *ptr;
void *win;
unsigned int mlx_width;
unsigned int mlx_height;
t_img **images;
t_maze *maze;
} t_mlx;
typedef struct s_colorpair {
struct s_colorpair *next;
unsigned int color1;
unsigned int color2;
} t_colorpair;
typedef struct s_func_data {
t_mlx *mlx;
t_colorpair *bundle;
t_colorpair *pair;
} t_func_data;
t_maze *init_grid(t_maze *maze);
void free_maze(t_maze *maze);
void generate_maze(t_maze *maze);
void pattern_42(t_maze *maze);
void set_seed(unsigned int s);
void solve(t_maze *maze);
int write_output(t_maze *maze);
int mlx_ready(t_mlx *mlx);
int mlx_render_grid(t_mlx *mlx,
unsigned int color1,
unsigned int color2);
int mlx_destroy(t_mlx *mlx);
int mlx_handle(int key, t_func_data *data);
int mlx_key_hook(void *win_ptr,
int (*funct_ptr)(int, t_func_data *),
void *param);
t_colorpair *init_bundle(void);
t_colorpair *random_pair(t_colorpair *bundle);
void free_bundle(t_colorpair *bundle);
void *mlx_init(void);
int mlx_loop(void *mlx_ptr);
"""
def __init__(self, lib_path: str = DEFAULT_LIB) -> None:
"""Load ``libamazing.so`` and prepare CFFI bindings.
:raises SystemExit: if the library cannot be loaded.
"""
self.ffi: FFI = FFI()
self.ffi.cdef(self._CDEF)
try:
self.lib: Any = self.ffi.dlopen(lib_path)
except OSError as exc:
print(
f"ERROR: cannot load {lib_path}: {exc}",
file=sys.stderr,
)
sys.exit(1)
self._anchor: dict[str, Any] = {}
def run(self, config_file: Optional[str] = None) -> None:
"""Parse config, generate, write output, then launch MLX.
Always cleans up the C maze and color bundle on exit.
:raises SystemExit: on user errors (missing config, malformed
values, allocation failures).
"""
cfg_path: str = config_file or DEFAULT_CONFIG
if not os.path.exists(cfg_path):
print(
f"ERROR: config file '{cfg_path}' not found.",
file=sys.stderr,
)
sys.exit(1)
try:
cfg: dict[str, Any] = _parse_config(cfg_path)
except (OSError, ValueError) as exc:
print(f"ERROR: {exc}", file=sys.stderr)
sys.exit(1)
maze_ptr: Any = self.ffi.new("t_maze *")
bundle: Any = self.ffi.NULL
try:
self._fill_maze(maze_ptr, cfg)
self._anchor["output"] = self.ffi.new(
"char[]", cfg["OUTPUT_FILE"].encode("utf-8")
)
maze_ptr.output_filename = self._anchor["output"]
self._seed_rng(cfg)
if not self.lib.init_grid(maze_ptr):
print(
"ERROR: failed to allocate maze grid",
file=sys.stderr,
)
sys.exit(1)
print(
f"Generating {int(maze_ptr.width)}x"
f"{int(maze_ptr.height)} maze..."
)
self.lib.pattern_42(maze_ptr)
self.lib.generate_maze(maze_ptr)
if not self.lib.write_output(maze_ptr):
print(
"ERROR: failed to write output file",
file=sys.stderr,
)
sys.exit(1)
print(f"Output written to {cfg['OUTPUT_FILE']}.")
bundle = self._launch_mlx(maze_ptr)
finally:
if bundle and bundle != self.ffi.NULL:
self.lib.free_bundle(bundle)
self.lib.free_maze(maze_ptr)
self._anchor.clear()
def _fill_maze(
self, maze_ptr: Any, cfg: dict[str, Any]
) -> None:
"""Copy parsed config fields onto the maze struct."""
maze_ptr.width = cfg["WIDTH"]
maze_ptr.height = cfg["HEIGHT"]
ex, ey = cfg["ENTRY"]
ox, oy = cfg["EXIT"]
maze_ptr.entry_x = ex
maze_ptr.entry_y = ey
maze_ptr.exit_x = ox
maze_ptr.exit_y = oy
maze_ptr.is_perfect = cfg["PERFECT"]
maze_ptr.is_solved = False
maze_ptr.imprate = int(cfg.get("IMPRATE", 50))
def _seed_rng(self, cfg: dict[str, Any]) -> None:
"""Seed the C RNG; default to a 32-bit time-derived value."""
seed: int = int(
cfg.get("SEED", time.time_ns() & 0xFFFFFFFF)
)
self.lib.set_seed(seed & 0xFFFFFFFF)
def _launch_mlx(self, maze_ptr: Any) -> Any:
"""Set up MLX, render, run the event loop. Returns the bundle.
Returns ``ffi.NULL`` if MLX initialization fails (so the caller
can still write the output file in headless contexts).
"""
mlx_ptr: Any = self.ffi.new("t_mlx *")
mlx_ptr.maze = maze_ptr
self._anchor["images"] = self.ffi.new("t_img *[64]")
mlx_ptr.images = self._anchor["images"]
self._anchor["mlx"] = mlx_ptr
if not self.lib.mlx_ready(mlx_ptr):
print(
"WARN: MLX init failed; output file already written.",
file=sys.stderr,
)
return self.ffi.NULL
bundle: Any = self.lib.init_bundle()
if bundle == self.ffi.NULL:
print(
"WARN: color bundle init failed; skipping render.",
file=sys.stderr,
)
return self.ffi.NULL
pair: Any = self.lib.random_pair(bundle)
if pair == self.ffi.NULL:
print(
"WARN: color pair selection failed; skipping render.",
file=sys.stderr,
)
return bundle
func_data: Any = self.ffi.new("t_func_data *")
func_data.mlx = mlx_ptr
func_data.bundle = bundle
func_data.pair = pair
self._anchor["func_data"] = func_data
print("Rendering maze...")
self.lib.mlx_render_grid(mlx_ptr, pair.color1, pair.color2)
self.lib.mlx_key_hook(
mlx_ptr.win, self.lib.mlx_handle, func_data
)
print(
"MLX loop: 1 (Regen), 2 (Solve), 3 (Color), 4 (Quit)."
)
self.lib.mlx_loop(mlx_ptr.ptr)
return bundle
def main() -> None:
"""CLI entry point. Parses ``sys.argv[1]`` as the config path."""
config_file: str = (
sys.argv[1] if len(sys.argv) > 1 else DEFAULT_CONFIG
)
MazeGenerator().run(config_file)
if __name__ == "__main__":
main()