1 file changed, +127, -11
2cd019drefactor(mazegen): imperfect mazes now always generate at least two solutions
author
mogi <git@mogiya.dev> on 31-05-2026 21:03 UTC+1
committer
mogi <git@mogiya.dev> on 31-05-2026 21:03 UTC+1
parent89bbf6d
+127, -11
      @@ -117,6 +117,7 @@ class MazeGenerator:
117117         if not self.perfect:
118118             yield from self._carve_rooms()
119119             yield from self._repair_3x3()
   120+            yield from self._carve_alt_route()
120121 
121122     def solve(self) -> None:
122123         """Solve the current maze, populating self.path."""
      @@ -190,6 +191,26 @@ class MazeGenerator:
190191         nx, ny = x + DX[direction], y + DY[direction]
191192         self.grid[ny][nx] |= OPPOSITE[direction]
192193 
   194+    def _step_bit(self, a: Position, b: Position) -> int:
   195+        """Return the wall bit for the step from a to grid-adjacent b."""
   196+        dx, dy = b[0] - a[0], b[1] - a[1]
   197+        for d in (N, E, S, W):
   198+            if DX[d] == dx and DY[d] == dy:
   199+                return d
   200+        raise MazegenError("cells are not grid-adjacent")
   201+
   202+    def _open_between(self, a: Position, b: Position) -> None:
   203+        """Open the wall between grid-adjacent cells a and b."""
   204+        self._open_wall(a[0], a[1], self._step_bit(a, b))
   205+
   206+    def _close_between(self, a: Position, b: Position) -> None:
   207+        """Close the wall between grid-adjacent cells a and b."""
   208+        self._close_wall(a[0], a[1], self._step_bit(a, b))
   209+
   210+    def _wall_closed_between(self, a: Position, b: Position) -> bool:
   211+        """True if the wall between grid-adjacent cells a and b is closed."""
   212+        return bool(self.grid[a[1]][a[0]] & self._step_bit(a, b))
   213+
193214     def _block_walls(self, x: int, y: int) -> list[tuple[int, int, int]]:
194215         """Return the 12 interior walls of the 3x3 block at (x, y)."""
195216         walls = [(x + dx, y + dy, E) for dy in range(3) for dx in range(2)]
      @@ -348,16 +369,16 @@ class MazeGenerator:
348369             add_edges(nx, ny)
349370             yield self.grid
350371 
351   -    def _solve_bfs(self) -> Iterator[Position]:
352   -        """BFS shortest path entry -> exit; yields each visited cell."""
353   -        entry = self.entry
354   -        exit_ = self.exit_
355   -        predecessor: dict[Position, Position] = {entry: entry}
356   -        queue: deque[Position] = deque([entry])
357   -        yield entry
   372+    def _bfs(
   373+        self, predecessor: dict[Position, Position]
   374+    ) -> Iterator[Position]:
   375+        """BFS from entry; fill predecessor map, yield each cell visited."""
   376+        queue: deque[Position] = deque([self.entry])
   377+        predecessor[self.entry] = self.entry
   378+        yield self.entry
358379         while queue:
359380             x, y = queue.popleft()
360   -            if (x, y) == exit_:
   381+            if (x, y) == self.exit_:
361382                 break
362383             cell = self.grid[y][x]
363384             for d in (N, E, S, W):
      @@ -369,11 +390,106 @@ class MazeGenerator:
369390                 predecessor[nxt] = (x, y)
370391                 queue.append(nxt)
371392                 yield nxt
372   -        if exit_ not in predecessor:
   393+
   394+    def _path_cells(self) -> list[Position]:
   395+        """Return the BFS entry->exit path as cells, or [] if unreachable."""
   396+        predecessor: dict[Position, Position] = {}
   397+        for _ in self._bfs(predecessor):
   398+            pass
   399+        if self.exit_ not in predecessor:
   400+            return []
   401+        cells: list[Position] = []
   402+        cur = self.exit_
   403+        while cur != self.entry:
   404+            cells.append(cur)
   405+            cur = predecessor[cur]
   406+        cells.append(self.entry)
   407+        cells.reverse()
   408+        return cells
   409+
   410+    def _alt_unsafe(self, cells: list[Position]) -> bool:
   411+        """True if opening these cells breaks the 3x3 or room-length caps."""
   412+        xs = [c[0] for c in cells]
   413+        ys = [c[1] for c in cells]
   414+        x0, y0 = min(xs), min(ys)
   415+        rw, rh = max(xs) - x0 + 1, max(ys) - y0 + 1
   416+        return self._region_creates_3x3(
   417+            x0, y0, rw, rh
   418+        ) or self._has_long_room(self._max_room_len)
   419+
   420+    def _add_chord(self, cells: list[Position]) -> bool:
   421+        """Open one wall joining two non-consecutive solution cells."""
   422+        index = {c: i for i, c in enumerate(cells)}
   423+        candidates: list[tuple[Position, Position]] = []
   424+        for i, (x, y) in enumerate(cells):
   425+            for nx, ny, d in self._neighbors(x, y):
   426+                j = index.get((nx, ny))
   427+                if j is None or abs(j - i) < 2:
   428+                    continue
   429+                if self.grid[y][x] & d:
   430+                    candidates.append(((x, y), (nx, ny)))
   431+        self._rng.shuffle(candidates)
   432+        for a, b in candidates:
   433+            self._open_between(a, b)
   434+            if self._alt_unsafe([a, b]):
   435+                self._close_between(a, b)
   436+                continue
   437+            return True
   438+        return False
   439+
   440+    def _add_detour(self, cells: list[Position]) -> bool:
   441+        """Open a 2x2 bypass around one solution edge."""
   442+        pairs = list(zip(cells, cells[1:]))
   443+        self._rng.shuffle(pairs)
   444+        for a, b in pairs:
   445+            ex, ey = b[0] - a[0], b[1] - a[1]
   446+            perps = [(-ey, ex), (ey, -ex)]
   447+            self._rng.shuffle(perps)
   448+            for px, py in perps:
   449+                a2 = (a[0] + px, a[1] + py)
   450+                b2 = (b[0] + px, b[1] + py)
   451+                if not (self._in_bounds(*a2) and self._in_bounds(*b2)):
   452+                    continue
   453+                if a2 in self.pattern_cells or b2 in self.pattern_cells:
   454+                    continue
   455+                steps = [(a, a2), (a2, b2), (b2, b)]
   456+                opened = [
   457+                    (u, v) for u, v in steps
   458+                    if self._wall_closed_between(u, v)
   459+                ]
   460+                if not opened:
   461+                    continue
   462+                for u, v in opened:
   463+                    self._open_between(u, v)
   464+                if self._alt_unsafe([a, b, a2, b2]):
   465+                    for u, v in opened:
   466+                        self._close_between(u, v)
   467+                    continue
   468+                return True
   469+        return False
   470+
   471+    def _carve_alt_route(self) -> Iterator[Grid]:
   472+        """Carve one extra passage so >= 2 entry->exit routes exist.
   473+
   474+        Tries a chord between two non-consecutive solution cells, then a
   475+        2x2 detour around a solution edge. The induced cycle always
   476+        overlaps the solution path, so the alternate route reaches exit.
   477+        """
   478+        cells = self._path_cells()
   479+        if len(cells) < 3:
   480+            return
   481+        if self._add_chord(cells) or self._add_detour(cells):
   482+            yield self.grid
   483+
   484+    def _solve_bfs(self) -> Iterator[Position]:
   485+        """BFS shortest path entry -> exit; yields each visited cell."""
   486+        predecessor: dict[Position, Position] = {}
   487+        yield from self._bfs(predecessor)
   488+        if self.exit_ not in predecessor:
373489             raise MazegenError("No path from entry to exit")
374490         path: list[str] = []
375   -        cur = exit_
376   -        while cur != entry:
   491+        cur = self.exit_
   492+        while cur != self.entry:
377493             prev = predecessor[cur]
378494             path.append(DELTA_DIR[(cur[0] - prev[0], cur[1] - prev[1])])
379495             cur = prev