Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
main ▾

Modern-Apps.git / scripts / pipes / generate_levels.py

generate_levels.py1056 lines · 33.7 KiBRaw
1#!/usr/bin/env python3
2"""Generate Flow/Pipes levels.
3
4Rectangular grids: Numberlink algorithm (Thomas Ahle) — paths fill the grid
5by construction. Levels validated with NumberLink solver (unique solution).
6"""
7import sys, json, random, subprocess, os
8from collections import defaultdict
9
10
11# ===================== Numberlink Generator =====================
12
13T, L, R = range(3)
14
15
16def sign(x):
17 if x == 0:
18 return x
19 return -1 if x < 0 else 1
20
21
22def unrotate(x, y, dx, dy):
23 while (dx, dy) != (0, 1):
24 x, y, dx, dy = -y, x, -dy, dx
25 return x, y
26
27
28class Path:
29 def __init__(self, steps):
30 self.steps = steps
31
32 def xys(self, dx=0, dy=1):
33 x, y = 0, 0
34 yield (x, y)
35 for step in self.steps:
36 x, y = x + dx, y + dy
37 yield (x, y)
38 if step == L:
39 dx, dy = -dy, dx
40 if step == R:
41 dx, dy = dy, -dx
42 elif step == T:
43 x, y = x + dx, y + dy
44 yield (x, y)
45
46 def test(self):
47 ps = list(self.xys())
48 return len(set(ps)) == len(ps)
49
50 def test_loop(self):
51 ps = list(self.xys())
52 seen = set(ps)
53 return len(ps) == len(seen) or (len(ps) == len(seen) + 1 and ps[0] == ps[-1])
54
55 def winding(self):
56 return self.steps.count(R) - self.steps.count(L)
57
58
59class UnionFind:
60 def __init__(self):
61 self.uf = {}
62
63 def union(self, a, b):
64 self.uf[self.find(a)] = self.find(b)
65
66 def find(self, a):
67 if self.uf.get(a, a) == a:
68 return a
69 par = self.find(self.uf.get(a, a))
70 self.uf[a] = par
71 return par
72
73
74class Mitm:
75 def __init__(self, lr_price=2, t_price=1):
76 self.lr_price = lr_price
77 self.t_price = t_price
78 self.inv = defaultdict(list)
79 self.list = []
80
81 def prepare(self, budget):
82 for path, (x, y, dx, dy) in self._good_paths(0, 0, 0, 1, budget):
83 self.list.append((path, x, y, dx, dy))
84 self.inv[x, y, dx, dy].append(path)
85
86 def rand_path2(self, xn, yn, dxn, dyn):
87 seen = set()
88 path = []
89 for _attempt in range(10000):
90 seen.clear()
91 del path[:]
92 x, y, dx, dy = 0, 0, 0, 1
93 seen.add((x, y))
94 for _ in range(2 * (abs(xn) + abs(yn))):
95 step, = random.choices(
96 [L, R, T],
97 [1 / self.lr_price, 1 / self.lr_price, 2 / self.t_price])
98 path.append(step)
99 x, y = x + dx, y + dy
100 if (x, y) in seen:
101 break
102 seen.add((x, y))
103 if step == L:
104 dx, dy = -dy, dx
105 if step == R:
106 dx, dy = dy, -dx
107 elif step == T:
108 x, y = x + dx, y + dy
109 if (x, y) in seen:
110 break
111 seen.add((x, y))
112 if (x, y) == (xn, yn):
113 return Path(path)
114 ends = self._lookup(dx, dy, xn - x, yn - y, dxn, dyn)
115 if ends:
116 return Path(tuple(path) + random.choice(ends))
117 return None
118
119 def rand_loop(self, clock=0):
120 for _attempt in range(10000):
121 path, x, y, dx, dy = random.choice(self.list)
122 path2s = self._lookup(dx, dy, -x, -y, 0, 1)
123 if path2s:
124 path2 = random.choice(path2s)
125 joined = Path(path + path2)
126 if clock and joined.winding() != clock * 4:
127 continue
128 if joined.test_loop():
129 return joined
130 return None
131
132 def _good_paths(self, x, y, dx, dy, budget, seen=None):
133 if seen is None:
134 seen = set()
135 if budget >= 0:
136 yield (), (x, y, dx, dy)
137 if budget <= 0:
138 return
139 seen.add((x, y))
140 x1, y1 = x + dx, y + dy
141 if (x1, y1) not in seen:
142 for path, end in self._good_paths(
143 x1, y1, -dy, dx, budget - self.lr_price, seen):
144 yield (L,) + path, end
145 for path, end in self._good_paths(
146 x1, y1, dy, -dx, budget - self.lr_price, seen):
147 yield (R,) + path, end
148 seen.add((x1, y1))
149 x2, y2 = x1 + dx, y1 + dy
150 if (x2, y2) not in seen:
151 for path, end in self._good_paths(
152 x2, y2, dx, dy, budget - self.t_price, seen):
153 yield (T,) + path, end
154 seen.remove((x1, y1))
155 seen.remove((x, y))
156
157 def _lookup(self, dx, dy, xn, yn, dxn, dyn):
158 xt, yt = unrotate(xn, yn, dx, dy)
159 dxt, dyt = unrotate(dxn, dyn, dx, dy)
160 return self.inv[xt, yt, dxt, dyt]
161
162
163class Grid:
164 def __init__(self, w, h):
165 self.w, self.h = w, h
166 self.grid = {}
167
168 def __setitem__(self, key, val):
169 self.grid[key] = val
170
171 def __getitem__(self, key):
172 return self.grid.get(key, ' ')
173
174 def __contains__(self, key):
175 return key in self.grid
176
177 def __iter__(self):
178 return iter(self.grid.items())
179
180 def clear(self):
181 self.grid.clear()
182
183 def values(self):
184 return self.grid.values()
185
186 def shrink(self):
187 small = Grid(self.w // 2, self.h // 2)
188 for y in range(self.h // 2):
189 for x in range(self.w // 2):
190 small[x, y] = self[2 * x + 1, 2 * y + 1]
191 return small
192
193 def test_path(self, path, x0, y0, dx0=0, dy0=1):
194 return all(
195 0 <= x0 - x + y < self.w and 0 <= y0 + x + y < self.h
196 and (x0 - x + y, y0 + x + y) not in self
197 for x, y in path.xys(dx0, dy0))
198
199 def draw_path(self, path, x0, y0, dx0=0, dy0=1, loop=False):
200 ps = list(path.xys(dx0, dy0))
201 if loop:
202 assert ps[0] == ps[-1]
203 ps.append(ps[1])
204 for i in range(1, len(ps) - 1):
205 xp, yp = ps[i - 1]
206 x, y = ps[i]
207 xn, yn = ps[i + 1]
208 self[x0 - x + y, y0 + x + y] = {
209 (1, 1, 1): '<', (-1, -1, -1): '<',
210 (1, 1, -1): '>', (-1, -1, 1): '>',
211 (-1, 1, 1): 'v', (1, -1, -1): 'v',
212 (-1, 1, -1): '^', (1, -1, 1): '^',
213 (0, 2, 0): '\\', (0, -2, 0): '\\',
214 (2, 0, 0): '/', (-2, 0, 0): '/'
215 }[xn - xp, yn - yp, sign((x - xp) * (yn - y) - (xn - x) * (y - yp))]
216
217 def make_tubes(self):
218 uf = UnionFind()
219 tube_grid = Grid(self.w, self.h)
220 for x in range(self.w):
221 d = '-'
222 for y in range(self.h):
223 for dx, dy in {
224 '/-': [(0, 1)], '\\-': [(1, 0), (0, 1)],
225 '/|': [(1, 0)],
226 ' -': [(1, 0)], ' |': [(0, 1)],
227 'v|': [(0, 1)], '>|': [(1, 0)],
228 'v-': [(0, 1)], '>-': [(1, 0)],
229 }.get(self[x, y] + d, []):
230 uf.union((x, y), (x + dx, y + dy))
231 tube_grid[x, y] = {
232 '/-': '┐', '\\-': '┌',
233 '/|': '└', '\\|': '┘',
234 ' -': '-', ' |': '|',
235 }.get(self[x, y] + d, 'x')
236 if self[x, y] in '\\/v^':
237 d = '|' if d == '-' else '-'
238 return tube_grid, uf
239
240 def clear_path(self, path, x, y):
241 path_grid = Grid(self.w, self.h)
242 path_grid.draw_path(path, x, y, loop=True)
243 for key, val in path_grid.make_tubes()[0]:
244 if val == '|':
245 self.grid.pop(key, None)
246
247
248LOOP_TRIES = 1000
249
250
251def has_loops(grid, uf):
252 groups = len({uf.find((x, y)) for y in range(grid.h) for x in range(grid.w)})
253 ends = sum(bool(grid[x, y] in 'v^<>') for y in range(grid.h) for x in range(grid.w))
254 return ends != 2 * groups
255
256
257def has_pair(tg, uf):
258 for y in range(tg.h):
259 for x in range(tg.w):
260 for dx, dy in ((1, 0), (0, 1)):
261 x1, y1 = x + dx, y + dy
262 if x1 < tg.w and y1 < tg.h:
263 if tg[x, y] == tg[x1, y1] == 'x' \
264 and uf.find((x, y)) == uf.find((x1, y1)):
265 return True
266 return False
267
268
269def has_tripple(tg, uf):
270 for y in range(tg.h):
271 for x in range(tg.w):
272 r = uf.find((x, y))
273 nbs = 0
274 for dx, dy in ((1, 0), (0, 1), (-1, 0), (0, -1)):
275 x1, y1 = x + dx, y + dy
276 if 0 <= x1 < tg.w and 0 <= y1 < tg.h and uf.find((x1, y1)) == r:
277 nbs += 1
278 if nbs >= 3:
279 return True
280 return False
281
282
283def make(w, h, mitm, min_numbers=0, max_numbers=1000):
284 def test_ready(grid):
285 sg = grid.shrink()
286 stg, uf = sg.make_tubes()
287 numbers = list(stg.values()).count('x') // 2
288 return (min_numbers <= numbers <= max_numbers
289 and not has_loops(sg, uf)
290 and not has_pair(stg, uf)
291 and not has_tripple(stg, uf))
292
293 grid = Grid(2 * w + 1, 2 * h + 1)
294
295 for _ in range(2000):
296 grid.clear()
297
298 path = mitm.rand_path2(h, h, 0, -1)
299 if path is None or not grid.test_path(path, 0, 0):
300 continue
301 grid.draw_path(path, 0, 0)
302 grid[0, 0], grid[0, 2 * h] = '\\', '/'
303
304 path2 = mitm.rand_path2(h, h, 0, -1)
305 if path2 is None or not grid.test_path(path2, 2 * w, 2 * h, 0, -1):
306 continue
307 grid.draw_path(path2, 2 * w, 2 * h, 0, -1)
308 grid[2 * w, 0], grid[2 * w, 2 * h] = '/', '\\'
309
310 if test_ready(grid):
311 return grid.shrink()
312
313 tg, _ = grid.make_tubes()
314 for tries in range(LOOP_TRIES):
315 x, y = 2 * random.randrange(w), 2 * random.randrange(h)
316 if tg[x, y] not in '-|':
317 continue
318 loop = mitm.rand_loop(clock=1 if tg[x, y] == '-' else -1)
319 if loop is None:
320 continue
321 if grid.test_path(loop, x, y):
322 grid.clear_path(loop, x, y)
323 grid.draw_path(loop, x, y, loop=True)
324 tg, _ = grid.make_tubes()
325
326 sg = grid.shrink()
327 stg, uf = sg.make_tubes()
328 numbers = list(stg.values()).count('x') // 2
329 if numbers > max_numbers:
330 break
331 if test_ready(grid):
332 return sg
333
334 return None
335
336
337def short_pair_violation(path_lengths):
338 """Reject too-easy puzzles based on flow (path) length in cells. The number
339 of empty squares between a pair's endpoints is (length - 2). Rules:
340 - no adjacent endpoints -> no flow of length <= 2 (0 between)
341 - <= 1 pair with 1 between -> at most one flow of length 3
342 - <= 2 pairs with <= 2 between -> at most two flows of length <= 4
343 """
344 if any(l <= 2 for l in path_lengths):
345 return True
346 if sum(1 for l in path_lengths if l == 3) > 1:
347 return True
348 if sum(1 for l in path_lengths if l <= 4) > 2:
349 return True
350 return False
351
352
353def grid_to_level(grid, level_id, w, h):
354 tube_grid, uf = grid.make_tubes()
355
356 group_sizes = {}
357 for y in range(grid.h):
358 for x in range(grid.w):
359 g = uf.find((x, y))
360 group_sizes[g] = group_sizes.get(g, 0) + 1
361
362 groups = defaultdict(list)
363 for y in range(grid.h):
364 for x in range(grid.w):
365 if tube_grid[x, y] == 'x':
366 groups[uf.find((x, y))].append([y, x])
367
368 endpoints = []
369 path_lengths = []
370 color = 0
371 for group_id, cells in groups.items():
372 if len(cells) == 2:
373 endpoints.append({"color": color, "cells": cells})
374 path_lengths.append(group_sizes[group_id])
375 color += 1
376
377 if not endpoints:
378 return None
379
380 if short_pair_violation(path_lengths):
381 return None
382
383 return {
384 "id": level_id,
385 "rows": h,
386 "cols": w,
387 "endpoints": endpoints,
388 "optimalMoves": len(endpoints)
389 }
390
391
392# ===================== Shape Masks (non-rectangular boards) =====================
393# Cells are (row, col) tuples. Every shape is a subset of a rectangular grid
394# with normal 4-neighbour adjacency; "holes" are grid cells not in the set.
395
396_DIRS4 = ((-1, 0), (1, 0), (0, -1), (0, 1))
397
398
399def compute_4_adjacency(cells):
400 """{cell: [neighbours]} using 4-neighbour adjacency restricted to cells."""
401 cellset = set(cells)
402 return {
403 (r, c): [(r + dr, c + dc) for dr, dc in _DIRS4 if (r + dr, c + dc) in cellset]
404 for (r, c) in cellset
405 }
406
407
408def is_connected(cells):
409 """True if the cell set is 4-connected (empty/singleton => True)."""
410 cellset = set(cells)
411 if len(cellset) <= 1:
412 return True
413 start = next(iter(cellset))
414 seen = {start}
415 stack = [start]
416 while stack:
417 r, c = stack.pop()
418 for dr, dc in _DIRS4:
419 n = (r + dr, c + dc)
420 if n in cellset and n not in seen:
421 seen.add(n)
422 stack.append(n)
423 return len(seen) == len(cellset)
424
425
426def largest_component(cells):
427 cellset = set(cells)
428 seen = set()
429 best = set()
430 for cell in cellset:
431 if cell in seen:
432 continue
433 comp = set()
434 stack = [cell]
435 seen.add(cell)
436 while stack:
437 r, c = stack.pop()
438 comp.add((r, c))
439 for dr, dc in _DIRS4:
440 n = (r + dr, c + dc)
441 if n in cellset and n not in seen:
442 seen.add(n)
443 stack.append(n)
444 if len(comp) > len(best):
445 best = comp
446 return best
447
448
449def normalize_cells(cells):
450 """Shift so the bounding box starts at (0, 0)."""
451 if not cells:
452 return set()
453 min_r = min(r for r, c in cells)
454 min_c = min(c for r, c in cells)
455 return {(r - min_r, c - min_c) for (r, c) in cells}
456
457
458def fill_interior_holes(cells):
459 """Fill empty cells fully enclosed by the shape (flood-fill from outside)."""
460 cellset = set(cells)
461 if not cellset:
462 return cellset
463 max_r = max(r for r, c in cellset)
464 max_c = max(c for r, c in cellset)
465 outside = set()
466 stack = [(-1, -1)]
467 while stack:
468 r, c = stack.pop()
469 if (r, c) in outside or (r, c) in cellset:
470 continue
471 if r < -1 or r > max_r + 1 or c < -1 or c > max_c + 1:
472 continue
473 outside.add((r, c))
474 for dr, dc in _DIRS4:
475 stack.append((r + dr, c + dc))
476 result = set(cellset)
477 for r in range(max_r + 1):
478 for c in range(max_c + 1):
479 if (r, c) not in cellset and (r, c) not in outside:
480 result.add((r, c))
481 return result
482
483
484def rect_cells(w, h):
485 """Full w×h rectangle."""
486 return {(r, c) for r in range(h) for c in range(w)}
487
488
489def hourglass_cells(w, h):
490 """Two full-width rectangles joined by a 1-column-wide neck."""
491 band = max(1, h // 3)
492 mid_col = w // 2
493 cells = set()
494 for r in range(band):
495 for c in range(w):
496 cells.add((r, c))
497 for r in range(h - band, h):
498 for c in range(w):
499 cells.add((r, c))
500 for r in range(band, h - band):
501 cells.add((r, mid_col))
502 return normalize_cells(cells)
503
504
505def _generate_blob(box, seed, disk_radius, target_fill, erosion_prob, roundness_bias):
506 """Seed a disk, accrete boundary cells (weighted toward present-neighbour
507 count for roundness), erode some boundary cells for lumpiness, fill holes,
508 keep the largest 4-connected component. Deterministic via seed."""
509 rng = random.Random(seed)
510 center = box // 2
511 cells = set()
512 for r in range(box):
513 for c in range(box):
514 if (r - center) ** 2 + (c - center) ** 2 <= disk_radius ** 2:
515 cells.add((r, c))
516 if not cells:
517 cells.add((center, center))
518 target = int(box * box * target_fill)
519
520 def present_neighbours(cell, s):
521 r, c = cell
522 return sum(1 for dr, dc in _DIRS4 if (r + dr, c + dc) in s)
523
524 guard = 0
525 while len(cells) < target and guard < box * box * 20:
526 guard += 1
527 frontier = set()
528 for (r, c) in cells:
529 for dr, dc in _DIRS4:
530 n = (r + dr, c + dc)
531 if 0 <= n[0] < box and 0 <= n[1] < box and n not in cells:
532 frontier.add(n)
533 if not frontier:
534 break
535 frontier = sorted(frontier)
536 weights = [present_neighbours(f, cells) ** roundness_bias for f in frontier]
537 cells.add(rng.choices(frontier, weights=weights)[0])
538
539 boundary = sorted(
540 cell for cell in cells
541 if any((cell[0] + dr, cell[1] + dc) not in cells for dr, dc in _DIRS4)
542 )
543 rng.shuffle(boundary)
544 for cell in boundary:
545 if rng.random() < erosion_prob:
546 trial = cells - {cell}
547 if trial and is_connected(trial):
548 cells = trial
549
550 cells = fill_interior_holes(cells)
551 cells = largest_component(cells)
552 return normalize_cells(cells)
553
554
555def blob_cells(size=8, seed=0):
556 """~size×size, roundish random connected shape."""
557 return _generate_blob(
558 box=size, seed=seed, disk_radius=size * 0.28,
559 target_fill=0.68, erosion_prob=0.15, roundness_bias=3.0)
560
561
562def inkblot_cells(size=13, seed=0):
563 """~size×size, larger and lumpier than blob."""
564 return _generate_blob(
565 box=size, seed=seed, disk_radius=size * 0.2,
566 target_fill=0.72, erosion_prob=0.35, roundness_bias=1.3)
567
568
569def walls_cells(n, seed=0):
570 """Full n×n with straight wall segments carved out; walls scale with n."""
571 rng = random.Random(seed)
572 cells = rect_cells(n, n)
573 num_walls = max(2, (n - 5) // 2 + 2)
574 max_len = min(6, n - 2)
575 placed = 0
576 guard = 0
577 while placed < num_walls and guard < num_walls * 50:
578 guard += 1
579 length = rng.randint(3, max(3, max_len))
580 if rng.random() < 0.5:
581 r = rng.randint(0, n - 1)
582 c0 = rng.randint(0, n - length)
583 seg = {(r, c0 + i) for i in range(length)}
584 else:
585 c = rng.randint(0, n - 1)
586 r0 = rng.randint(0, n - length)
587 seg = {(r0 + i, c) for i in range(length)}
588 trial = cells - seg
589 if len(trial) >= 2 and is_connected(trial):
590 cells = trial
591 placed += 1
592 return normalize_cells(cells)
593
594
595# ===================== Graph-based Carve Generator (masked boards) =====================
596# Python port of LevelGenerator.tryGenerate (Kotlin). Greedily builds flows over
597# the cell set, only extending into cells whose removal keeps the remaining
598# unmarked set connected, so the board is fully covered by construction.
599
600def articulation_points(nodes, adjacency):
601 """Cut vertices of the subgraph induced by `nodes` (iterative Tarjan). A cell
602 is a cut vertex iff removing it disconnects the (connected) node set — so
603 `cell not in articulation_points(nodes)` == "removing cell keeps connected"."""
604 if len(nodes) <= 2:
605 return set()
606 disc = {}
607 low = {}
608 ap = set()
609 timer = 0
610 for root in nodes:
611 if root in disc:
612 continue
613 root_children = 0
614 parent = {root: None}
615 disc[root] = low[root] = timer
616 timer += 1
617 stack = [(root, iter(adjacency[root]))]
618 while stack:
619 node, it = stack[-1]
620 descended = False
621 for nb in it:
622 if nb not in nodes:
623 continue
624 if nb not in disc:
625 parent[nb] = node
626 disc[nb] = low[nb] = timer
627 timer += 1
628 stack.append((nb, iter(adjacency[nb])))
629 if node == root:
630 root_children += 1
631 descended = True
632 break
633 elif nb != parent[node]:
634 low[node] = min(low[node], disc[nb])
635 if not descended:
636 stack.pop()
637 if stack:
638 par = stack[-1][0]
639 low[par] = min(low[par], low[node])
640 if parent[par] is not None and low[node] >= disc[par]:
641 ap.add(par)
642 if root_children > 1:
643 ap.add(root)
644 return ap
645
646
647def _connected_after_removal(unmarked, adjacency, candidate):
648 remaining = unmarked - {candidate}
649 if len(remaining) <= 1:
650 return True
651 start = next(iter(remaining))
652 seen = {start}
653 stack = [start]
654 while stack:
655 cur = stack.pop()
656 for nb in adjacency[cur]:
657 if nb in remaining and nb not in seen:
658 seen.add(nb)
659 stack.append(nb)
660 return len(seen) == len(remaining)
661
662
663def _pick_start(unmarked, adjacency, rng, cut_points=None):
664 """Prefer a start cell whose removal keeps the unmarked set connected, so a
665 flow never immediately strands a region."""
666 if cut_points is None:
667 cut_points = articulation_points(unmarked, adjacency)
668 candidates = sorted(unmarked)
669 rng.shuffle(candidates)
670 for cand in candidates:
671 if cand not in cut_points:
672 return cand
673 return candidates[0]
674
675
676def carve_try(cells, adjacency, num_flows, rng):
677 """One carve attempt. Returns list of paths (each a list of cells) or None."""
678 unmarked = set(cells)
679 paths = []
680 for flow_index in range(num_flows):
681 if not unmarked:
682 break
683 is_last = flow_index == num_flows - 1
684 start = _pick_start(unmarked, adjacency, rng)
685 path = [start]
686 unmarked.discard(start)
687
688 if is_last:
689 max_len = len(unmarked) + 1
690 min_len = max_len
691 else:
692 min_len = 3
693 max_len = len(unmarked) - (num_flows - flow_index - 1) * 2
694
695 while len(path) < max_len:
696 current = path[-1]
697 neighbors = [n for n in adjacency[current] if n in unmarked]
698 rng.shuffle(neighbors)
699 valid = [n for n in neighbors
700 if _connected_after_removal(unmarked, adjacency, n)]
701 if not valid:
702 break
703 nxt = valid[0]
704 path.append(nxt)
705 unmarked.discard(nxt)
706 if not is_last and len(path) >= min_len and rng.random() < 0.3:
707 break
708
709 if len(path) < 2:
710 return None
711 paths.append(path)
712
713 if unmarked:
714 return None
715 return paths
716
717
718def carve_cover(cells, adjacency, rng, early_stop_prob=0.25):
719 """Path-cover with a dynamic number of flows: keep carving connectivity-
720 preserving paths until every cell is used. Higher early_stop_prob yields
721 more (shorter) flows. Retries a stranded start a few times before giving up.
722 Returns list of paths or None if a cell cannot be covered.
723
724 `remaining` is kept connected as an invariant, so "removing a cell keeps the
725 set connected" reduces to "the cell is not an articulation point". We compute
726 all articulation points once per step (O(V+E)) and take the first valid
727 neighbour, instead of a BFS per candidate."""
728 unmarked = set(cells)
729 paths = []
730 while unmarked:
731 chosen = None
732 for _retry in range(8):
733 remaining = set(unmarked)
734 cut = articulation_points(remaining, adjacency)
735 start = _pick_start(remaining, adjacency, rng, cut)
736 path = [start]
737 remaining.discard(start)
738 while remaining:
739 current = path[-1]
740 cut = articulation_points(remaining, adjacency)
741 neighbors = [n for n in adjacency[current] if n in remaining]
742 rng.shuffle(neighbors)
743 nxt = next((n for n in neighbors if n not in cut), None)
744 if nxt is None:
745 break
746 path.append(nxt)
747 remaining.discard(nxt)
748 if len(path) >= 3 and rng.random() < early_stop_prob:
749 break
750 if len(path) >= 2:
751 chosen = path
752 unmarked = remaining
753 break
754 if chosen is None:
755 return None
756 paths.append(chosen)
757 return paths
758
759
760# ===================== Solver Validation =====================
761
762SOLVER_DIR = os.path.dirname(os.path.abspath(__file__))
763SOLVER_SRC = os.path.join(SOLVER_DIR, "numberlink_solver.cpp")
764SOLVER_BIN = os.path.join(SOLVER_DIR, "numberlink_solver")
765
766
767def compile_solver():
768 if os.path.exists(SOLVER_BIN) and os.path.getmtime(SOLVER_BIN) >= os.path.getmtime(SOLVER_SRC):
769 return True
770 print("Compiling NumberLink solver...")
771 result = subprocess.run(
772 ["g++", "-O2", "-o", SOLVER_BIN, SOLVER_SRC],
773 capture_output=True, text=True
774 )
775 if result.returncode != 0:
776 print(f"Failed to compile solver: {result.stderr}", file=sys.stderr)
777 return False
778 return True
779
780
781def validate_unique_solution(level, timeout=60):
782 rows, cols = level["rows"], level["cols"]
783 mask = {(r, c) for r, c in level["cells"]} if "cells" in level else None
784 grid = [
785 [0 if (mask is None or (r, c) in mask) else -1 for c in range(cols)]
786 for r in range(rows)
787 ]
788 for ep in level["endpoints"]:
789 color_num = ep["color"] + 1
790 for r, c in ep["cells"]:
791 grid[r][c] = color_num
792
793 input_str = f"{cols} {rows}\n"
794 for row in grid:
795 input_str += " ".join(str(v) for v in row) + "\n"
796
797 try:
798 result = subprocess.run(
799 [SOLVER_BIN],
800 input=input_str, capture_output=True, text=True, timeout=timeout
801 )
802 except subprocess.TimeoutExpired:
803 return False
804 if result.returncode != 0:
805 return False
806
807 for line in result.stdout.strip().split("\n"):
808 if "# of solutions:" in line:
809 count_str = line.split(":")[-1].strip()
810 try:
811 count = int(float(count_str))
812 return count == 1
813 except ValueError:
814 return False
815 return False
816
817
818# ===================== Pack Generation =====================
819
820def carve_to_level(cells, paths, level_id):
821 endpoints = [
822 {"color": i, "cells": [list(path[0]), list(path[-1])]}
823 for i, path in enumerate(paths)
824 ]
825 rows = max(r for r, c in cells) + 1
826 cols = max(c for r, c in cells) + 1
827 return {
828 "id": level_id,
829 "rows": rows,
830 "cols": cols,
831 "cells": sorted([list(cell) for cell in cells]),
832 "endpoints": endpoints,
833 "optimalMoves": len(endpoints),
834 }
835
836
837def generate_rect_pack(name, w, h, num_levels, flow_range, base_seed):
838 # Cap the MITM loop budget: beyond ~12 the precomputed path tables make each
839 # `make` call dramatically slower with no quality gain (9× slower at 15×15).
840 budget = min(12, max(h, 6))
841 mitm = Mitm(lr_price=2, t_price=1)
842 mitm.prepare(budget)
843
844 # On large boards the ZDD solver can take minutes on the rare hard instance;
845 # cap validation low and just move on — there are plenty of candidates.
846 val_timeout = 10 if h >= 11 else 60
847
848 levels = []
849 seed = base_seed
850 max_attempts = num_levels * 500
851 attempts = 0
852 while len(levels) < num_levels and attempts < max_attempts:
853 random.seed(seed)
854 min_n, max_n = flow_range
855 grid = make(w, h, mitm, min_n, max_n)
856 if grid is not None:
857 lid = f"{name.replace(' ', '_')}_{len(levels)+1:03d}"
858 level = grid_to_level(grid, lid, w, h)
859 if level is not None and validate_unique_solution(level, val_timeout):
860 levels.append(level)
861 sys.stdout.write(f"\r {len(levels)}/{num_levels}")
862 sys.stdout.flush()
863 seed += 1
864 attempts += 1
865 print()
866 return levels
867
868
869def generate_tower_pack(name, w, heights, base_seed):
870 """Pure (non-square) rectangles of width w with per-level heights. No cells
871 key emitted — the loader defaults to a full rectangle from rows/cols."""
872 num_levels = len(heights)
873 levels = []
874 seed = base_seed
875 mitms = {}
876 attempts = 0
877 max_attempts = num_levels * 500
878 while len(levels) < num_levels and attempts < max_attempts:
879 attempts += 1
880 h = heights[len(levels)]
881 if h not in mitms:
882 m = Mitm(lr_price=2, t_price=1)
883 m.prepare(min(12, max(h, 6)))
884 mitms[h] = m
885 random.seed(seed)
886 seed += 1
887 grid = make(w, h, mitms[h], max(3, (w + h) // 4), w + h)
888 if grid is None:
889 continue
890 lid = f"{name}_{len(levels)+1:03d}"
891 level = grid_to_level(grid, lid, w, h)
892 if level is not None and validate_unique_solution(level):
893 levels.append(level)
894 sys.stdout.write(f"\r {len(levels)}/{num_levels}")
895 sys.stdout.flush()
896 print()
897 return levels
898
899
900def flow_ceiling(cells):
901 """Max flows (endpoint pairs) allowed for a board of this size, so puzzles
902 stay sparse with longer flows instead of a swarm of tiny 2-cell pairs.
903 ~cells/5 keeps the average flow length around 5+."""
904 return max(4, round(len(cells) / 5))
905
906
907def generate_masked_pack(name, shape_fn, num_levels, base_seed,
908 early_stop=0.0, attempts_per_level=800):
909 """Generate masked (non-rectangular) levels via the carve path-cover, keeping
910 only uniquely-solvable ones with at most flow_ceiling(cells) flows.
911 shape_fn(level_index, seed) -> set of cells."""
912 levels = []
913 seed = base_seed
914 attempts = 0
915 max_attempts = num_levels * attempts_per_level
916 while len(levels) < num_levels and attempts < max_attempts:
917 attempts += 1
918 cells = shape_fn(len(levels), seed)
919 seed += 1
920 if len(cells) < 6 or not is_connected(cells):
921 continue
922 adjacency = compute_4_adjacency(cells)
923 paths = carve_cover(cells, adjacency, random.Random(seed), early_stop)
924 if not paths or len(paths) > flow_ceiling(cells):
925 continue
926 if short_pair_violation([len(p) for p in paths]):
927 continue
928 lid = f"{name}_{len(levels)+1:03d}"
929 level = carve_to_level(cells, paths, lid)
930 if validate_unique_solution(level, 10):
931 levels.append(level)
932 sys.stdout.write(f"\r {len(levels)}/{num_levels} (attempts {attempts})")
933 sys.stdout.flush()
934 print()
935 return levels
936
937
938def square_flow_range(n):
939 # Larger boards need more flows (endpoints) to stay uniquely solvable and to
940 # keep the solver fast; small boards keep their original sparser ranges.
941 if n <= 7:
942 return (max(3, n // 2), n + 3)
943 if n <= 10:
944 return (n, 2 * n - 2)
945 return (n + 2, 2 * n - 2)
946
947
948# (filename_stem, display_name, shape_label, builder) — builder returns levels.
949def build_registry():
950 reg = []
951
952 # Squares: 5×5 … 14×14 (5/6/7 are the existing packs, unchanged).
953 square_seeds = {5: 10000, 6: 20000, 7: 30000}
954 for n in range(8, 15):
955 square_seeds[n] = n * 10000
956 for n in range(5, 15):
957 reg.append((
958 f"{n}x{n}", f"{n}×{n}", "rectangular",
959 (lambda n=n: {
960 "name": f"{n}×{n}", "shape": "rectangular",
961 "levels": generate_rect_pack(
962 f"{n}×{n}", n, n, 30, square_flow_range(n), square_seeds[n]),
963 })
964 ))
965
966 # Tower: width 6, heights 8..12 (6 levels each => 30).
967 heights = [8] * 6 + [9] * 6 + [10] * 6 + [11] * 6 + [12] * 6
968 reg.append((
969 "tower", "Tower", "tower",
970 lambda: {
971 "name": "Tower", "shape": "tower",
972 "levels": generate_tower_pack("Tower", 6, heights, 40000),
973 }
974 ))
975
976 # Hourglass: small bounding sizes (≤ ~59 cells) so a few long flows still
977 # solve uniquely; larger boards force too many pairs / lose uniqueness.
978 hg_feasible = [(8, 10), (9, 10), (8, 11), (9, 11)]
979 hg_sizes = [hg_feasible[i % len(hg_feasible)] for i in range(30)]
980
981 def hourglass_shape(idx, seed):
982 w, h = hg_sizes[idx]
983 return hourglass_cells(w, h)
984
985 reg.append((
986 "hourglass", "Hourglass", "hourglass",
987 lambda: {
988 "name": "Hourglass", "shape": "hourglass",
989 "levels": generate_masked_pack(
990 "Hourglass", hourglass_shape, 30, 50000),
991 }
992 ))
993
994 # Blob: small round shapes (shape varies with seed).
995 def blob_shape(idx, seed):
996 return blob_cells(7 + (idx * 2) // 30, seed) # 7..8
997
998 reg.append((
999 "blob", "Blob", "blob",
1000 lambda: {
1001 "name": "Blob", "shape": "blob",
1002 "levels": generate_masked_pack("Blob", blob_shape, 30, 60000),
1003 }
1004 ))
1005
1006 # Inkblot: small lumpier random shapes. Kept at 8 — larger inkblots can't
1007 # satisfy the sparse short-pair rule while staying uniquely solvable.
1008 def inkblot_shape(idx, seed):
1009 return inkblot_cells(8, seed)
1010
1011 reg.append((
1012 "inkblot", "Inkblot", "inkblot",
1013 lambda: {
1014 "name": "Inkblot", "shape": "inkblot",
1015 "levels": generate_masked_pack(
1016 "Inkblot", inkblot_shape, 30, 70000, attempts_per_level=2000),
1017 }
1018 ))
1019
1020 # Walls: small base sizes 7..8 with carved wall segments.
1021 def walls_shape(idx, seed):
1022 n = 7 + (idx * 2) // 30 # 7..8
1023 return walls_cells(n, seed)
1024
1025 reg.append((
1026 "walls", "Walls", "walls",
1027 lambda: {
1028 "name": "Walls", "shape": "walls",
1029 "levels": generate_masked_pack("Walls", walls_shape, 30, 80000),
1030 }
1031 ))
1032
1033 return reg
1034
1035
1036def main():
1037 out_dir = sys.argv[1] if len(sys.argv) > 1 else "."
1038 selected = set(sys.argv[2:]) # optional filename stems to (re)generate
1039
1040 if not compile_solver():
1041 print("Error: Could not compile NumberLink solver", file=sys.stderr)
1042 sys.exit(1)
1043
1044 for stem, display, _shape, builder in build_registry():
1045 if selected and stem not in selected:
1046 continue
1047 print(f"Generating {display}...")
1048 pack_data = builder()
1049 path = f"{out_dir}/{stem}.json"
1050 with open(path, "w") as f:
1051 json.dump(pack_data, f, indent=2)
1052 print(f" -> {len(pack_data['levels'])} levels written to {path}")
1053
1054
1055if __name__ == "__main__":
1056 main()