puzzleworks 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,148 @@
1
+ """Generate printable and interactive puzzles from Python."""
2
+
3
+ from collections.abc import Mapping
4
+ from copy import deepcopy
5
+ from importlib import import_module, resources
6
+ from typing import NamedTuple
7
+
8
+ from ._runtime import generation_context, output_directory
9
+
10
+ __all__ = ["defaults", "generate", "puzzles"]
11
+
12
+
13
+ class _Puzzle(NamedTuple):
14
+ module: str
15
+ entry: str
16
+ formats: tuple[str, ...]
17
+ accepts_settings: bool = True
18
+
19
+
20
+ _PUZZLES = {
21
+ "center-stage": _Puzzle("center_stage", "generate_center_stage", ("png",)),
22
+ "cipher": _Puzzle("cipher", "generate", ("html", "png", "pdf")),
23
+ "compound-path": _Puzzle("compound_path", "generate", ("png",)),
24
+ "criss-cross": _Puzzle("criss_cross", "create_crisscross", ("png", "pdf", "html")),
25
+ "criss-cross-shape": _Puzzle("criss_cross_shape", "create_puzzle", ("png", "pdf")),
26
+ "crossword": _Puzzle("crossword", "generate_crossword", ("png", "pdf"), False),
27
+ "jumble": _Puzzle("jumble", "generate_jumble", ("html", "png")),
28
+ "masyu": _Puzzle("masyu", "generate_masyu", ("png",)),
29
+ "maze-letter": _Puzzle("maze_letter", "generate", ("html", "png", "pdf")),
30
+ "maze-perfect": _Puzzle("maze_perfect", "create_maze", ("html", "png"), False),
31
+ "regions": _Puzzle("regions", "main", ("png", "pdf"), False),
32
+ "single-word-search": _Puzzle("single_word_search", "main", ("png",), False),
33
+ "stacked-puzzle": _Puzzle("stacked_puzzle", "generate", ("png", "pdf")),
34
+ "word-find": _Puzzle("word_find", "generate", ("html", "png", "pdf")),
35
+ "word-ladder": _Puzzle("word_ladder", "main", ("html", "png", "both"), False),
36
+ "word-spiral": _Puzzle("word_spiral", "run_puzzle", ("png", "pdf"), False),
37
+ }
38
+
39
+ _COMPOUND_ALIASES = {
40
+ "output_dir": ("output", "output_dir"),
41
+ "output_basename": ("output", "basename"),
42
+ "save_to_desktop": ("output", "save_to_desktop"),
43
+ "dpi": ("output", "dpi"),
44
+ "font_path": ("text", "font_path"),
45
+ "background_color": ("colors", "background"),
46
+ "cell_size": ("grid", "cell_size"),
47
+ }
48
+ _ALIASES = {
49
+ "masyu": {"seed": "random_seed"},
50
+ "maze-perfect": {"cell_size": "cell_px"},
51
+ "word-ladder": {"title_text": "title", "key_title_text": "key_title"},
52
+ }
53
+
54
+
55
+ def puzzles() -> dict[str, tuple[str, ...]]:
56
+ """Return the supported puzzle names and their available output formats."""
57
+ return {name: puzzle.formats for name, puzzle in _PUZZLES.items()}
58
+
59
+
60
+ def _resolve(name):
61
+ canonical = name.strip().lower().replace("_", "-")
62
+ if canonical not in _PUZZLES:
63
+ raise ValueError(f"Unknown puzzle {name!r}. Choose from {', '.join(_PUZZLES)}.")
64
+ puzzle = _PUZZLES[canonical]
65
+ module = import_module(f"._generators.{puzzle.module}", __name__)
66
+ return canonical, puzzle, module
67
+
68
+
69
+ def _defaults(name, puzzle, module):
70
+ options = deepcopy(module.SETTINGS)
71
+ output = options["output"] if name == "compound-path" else options
72
+ output.update(output_dir=None, save_to_desktop=False)
73
+ options["output_type"] = options.get("output_type", puzzle.formats[0]).lower()
74
+ # These generators previously drew from Python's unconfigured global RNG.
75
+ if name in {"criss-cross", "regions", "stacked-puzzle"}:
76
+ options["seed"] = None
77
+ return options
78
+
79
+
80
+ def defaults(name: str) -> dict:
81
+ """Return a fresh copy of one generator's settings."""
82
+ return _defaults(*_resolve(name))
83
+
84
+
85
+ def _merge(target, overrides):
86
+ for key, value in overrides.items():
87
+ if key not in target:
88
+ raise ValueError(f"Unknown setting {key!r}. Use defaults(name) to see the settings.")
89
+ if isinstance(target[key], dict):
90
+ if not isinstance(value, Mapping):
91
+ raise TypeError(f"The {key!r} setting must be a mapping.")
92
+ _merge(target[key], value)
93
+ else:
94
+ target[key] = deepcopy(value)
95
+
96
+
97
+ def _apply(name, target, overrides):
98
+ if name == "compound-path":
99
+ other = {key: value for key, value in overrides.items() if key not in _COMPOUND_ALIASES}
100
+ _merge(target, other)
101
+ for alias, (group, key) in _COMPOUND_ALIASES.items():
102
+ if alias in overrides:
103
+ target[group][key] = deepcopy(overrides[alias])
104
+ else:
105
+ aliases = _ALIASES.get(name, {})
106
+ normal = {aliases.get(key, key): value for key, value in overrides.items()}
107
+ _merge(target, normal)
108
+
109
+
110
+ def generate(name: str, *inputs, settings: Mapping | None = None, **overrides) -> None:
111
+ """Generate a puzzle using its required inputs and write its files to disk."""
112
+ name, puzzle, module = _resolve(name)
113
+ options = _defaults(name, puzzle, module)
114
+ if settings is not None:
115
+ _apply(name, options, settings)
116
+ _apply(name, options, overrides)
117
+ output_type = options["output_type"].strip().lower()
118
+ if output_type not in puzzle.formats:
119
+ raise ValueError(f"{name} supports these output formats: {', '.join(puzzle.formats)}.")
120
+ options["output_type"] = output_type
121
+
122
+ output = options["output"] if name == "compound-path" else options
123
+ output["output_dir"] = output_directory(output)
124
+ output["output_dir"].mkdir(parents=True, exist_ok=True)
125
+
126
+ def run():
127
+ with generation_context(options):
128
+ entry = getattr(module, puzzle.entry)
129
+ if puzzle.accepts_settings:
130
+ entry(*inputs, settings=options)
131
+ else:
132
+ entry(*inputs)
133
+
134
+ if name in {"maze-perfect", "criss-cross-shape"}:
135
+ shape = options["shape"].strip().lower()
136
+ if shape == "heart":
137
+ options["shape"] = "mask"
138
+ if name == "maze-perfect":
139
+ options["mask_preserve_aspect"] = True
140
+ heart = resources.files(__name__).joinpath("masks", "heart.png")
141
+ with resources.as_file(heart) as path:
142
+ options["mask_path"] = path
143
+ run()
144
+ return
145
+ if options["mask_path"] and "shape" not in (settings or {}) and "shape" not in overrides:
146
+ shape = "mask"
147
+ options["shape"] = shape
148
+ run()
File without changes
@@ -0,0 +1,235 @@
1
+ from pathlib import Path
2
+ from typing import List, Optional
3
+ from PIL import Image, ImageDraw, ImageFont
4
+
5
+ from .._runtime import output_directory
6
+
7
+ # =========================
8
+ # SETTINGS
9
+ # =========================
10
+ SETTINGS = {
11
+ "output_basename": "center_stage",
12
+ "dpi": 300,
13
+
14
+ "cell_size": 120,
15
+ "outer_margin": 100,
16
+ "title_gap": 100,
17
+
18
+ # Title cells
19
+ "title_cell_scale": 0.75, # 75% smaller than grid cells
20
+ "title_font_scale": 0.48,
21
+ "title_cells_bold": True,
22
+ "title_cell_gap": 8, # space between title cells
23
+
24
+ # Grid letters
25
+ "letter_font_scale": 0.55,
26
+ "outer_letters_bold": False,
27
+ "center_letters_bold": True,
28
+
29
+ # Stroke / corners
30
+ "grid_line_width": 4,
31
+ "cell_corner_radius_ratio": 0.12,
32
+
33
+ # Colors
34
+ "background_color": "#FFFFFF",
35
+ "grid_color": (0, 0, 0),
36
+ "letter_color": (0, 0, 0),
37
+
38
+ # Very dark red title
39
+ "title_color": (85, 10, 15),
40
+
41
+ # Shared shading
42
+ "shade_fill_color": (210, 220, 230),
43
+
44
+ "font_path": None,
45
+ }
46
+
47
+
48
+ # =========================
49
+ # COLOR HELPER
50
+ # =========================
51
+ def lighten_color(color, factor=0.40):
52
+ r, g, b = color
53
+ r = int(r + (255 - r) * factor)
54
+ g = int(g + (255 - g) * factor)
55
+ b = int(b + (255 - b) * factor)
56
+ return (r, g, b)
57
+
58
+
59
+ # =========================
60
+ # HELPERS
61
+ # =========================
62
+ def get_output_dir(settings):
63
+ return output_directory(settings)
64
+
65
+
66
+ def load_font(font_path: Optional[str], size: int, bold: bool = False):
67
+ if font_path:
68
+ return ImageFont.truetype(font_path, size)
69
+
70
+ candidates = []
71
+ if bold:
72
+ candidates += ["DejaVuSans-Bold.ttf", "arialbd.ttf"]
73
+ candidates += ["DejaVuSans.ttf", "arial.ttf"]
74
+
75
+ for name in candidates:
76
+ try:
77
+ return ImageFont.truetype(name, size)
78
+ except Exception:
79
+ continue
80
+ return ImageFont.load_default()
81
+
82
+
83
+ def in_shape(r, c):
84
+ return (r in (1, 2, 3)) or (c in (1, 2, 3))
85
+
86
+
87
+ def in_center(r, c):
88
+ return 1 <= r <= 3 and 1 <= c <= 3
89
+
90
+
91
+ def build_grid(across, down):
92
+ grid = [["" for _ in range(5)] for _ in range(5)]
93
+
94
+ for r in range(3):
95
+ for c in range(5):
96
+ grid[r + 1][c] = across[r].upper()[c]
97
+
98
+ for c in range(3):
99
+ for r in range(5):
100
+ grid[r][c + 1] = down[c].upper()[r]
101
+
102
+ return grid
103
+
104
+
105
+ def center_text(d, x, y, cs, text, font, fill):
106
+ bb = d.textbbox((0, 0), text, font=font)
107
+ tw = bb[2] - bb[0]
108
+ th = bb[3] - bb[1]
109
+ tx = x + (cs - tw) / 2 - bb[0]
110
+ ty = y + (cs - th) / 2 - bb[1]
111
+ d.text((tx, ty), text, font=font, fill=fill)
112
+
113
+
114
+ # =========================
115
+ # DRAW
116
+ # =========================
117
+ def draw_center_stage(across, down, center_word, settings, show_solution):
118
+
119
+ cs = settings["cell_size"]
120
+ margin = settings["outer_margin"]
121
+ lw = settings["grid_line_width"]
122
+ radius = int(cs * settings["cell_corner_radius_ratio"])
123
+
124
+ if len(center_word) != 9:
125
+ raise ValueError("center_word must be exactly 9 letters.")
126
+
127
+ center_word = center_word.upper()
128
+ grid = build_grid(across, down)
129
+
130
+ # Smaller title cells
131
+ title_cs = int(cs * settings["title_cell_scale"])
132
+ title_radius = int(title_cs * settings["cell_corner_radius_ratio"])
133
+ gap_between_title = settings.get("title_cell_gap", 0)
134
+
135
+ W = margin * 2 + cs * 9
136
+ H = margin * 2 + title_cs + settings["title_gap"] + cs * 5
137
+
138
+ img = Image.new("RGB", (W, H), settings["background_color"])
139
+ d = ImageDraw.Draw(img)
140
+
141
+ # Derived border color
142
+ accent_border = lighten_color(settings["title_color"], 0.15)
143
+
144
+ # Fonts
145
+ title_font = load_font(
146
+ settings["font_path"],
147
+ int(title_cs * settings["title_font_scale"]),
148
+ bold=settings["title_cells_bold"]
149
+ )
150
+
151
+ base_size = int(cs * settings["letter_font_scale"])
152
+ outer_font = load_font(settings["font_path"], base_size, bold=settings["outer_letters_bold"])
153
+ center_font = load_font(settings["font_path"], base_size, bold=settings["center_letters_bold"])
154
+
155
+ # -------------------------
156
+ # TITLE ROW
157
+ # -------------------------
158
+ row_w = title_cs * 9 + gap_between_title * 8
159
+ tx0 = margin + (cs * 9 - row_w) // 2
160
+ ty0 = margin
161
+
162
+ for i, ch in enumerate(center_word):
163
+ x = tx0 + i * (title_cs + gap_between_title)
164
+ y = ty0
165
+
166
+ d.rounded_rectangle(
167
+ [x, y, x + title_cs, y + title_cs],
168
+ radius=title_radius,
169
+ outline=accent_border,
170
+ width=lw,
171
+ fill=settings["shade_fill_color"]
172
+ )
173
+
174
+ center_text(d, x, y, title_cs, ch, title_font, settings["title_color"])
175
+
176
+ # -------------------------
177
+ # GRID
178
+ # -------------------------
179
+ gx = margin + (cs * 9 - cs * 5) // 2
180
+ gy = margin + title_cs + settings["title_gap"]
181
+
182
+ for r in range(5):
183
+ for c in range(5):
184
+ if not in_shape(r, c):
185
+ continue
186
+
187
+ x = gx + c * cs
188
+ y = gy + r * cs
189
+
190
+ is_center = in_center(r, c)
191
+
192
+ border_color = accent_border if is_center else settings["grid_color"]
193
+ fill = settings["shade_fill_color"] if is_center else None
194
+
195
+ d.rounded_rectangle(
196
+ [x, y, x + cs, y + cs],
197
+ radius=radius,
198
+ outline=border_color,
199
+ width=lw,
200
+ fill=fill
201
+ )
202
+
203
+ if not show_solution and is_center:
204
+ continue
205
+
206
+ letter = grid[r][c]
207
+ if letter:
208
+ font = center_font if is_center else outer_font
209
+ center_text(d, x, y, cs, letter, font, settings["letter_color"])
210
+
211
+ return img
212
+
213
+
214
+ # =========================
215
+ # GENERATOR
216
+ # =========================
217
+ def generate_center_stage(across_words, down_words, center_word, settings=SETTINGS):
218
+
219
+ puzzle = draw_center_stage(across_words, down_words, center_word, settings, False)
220
+ key = draw_center_stage(across_words, down_words, center_word, settings, True)
221
+
222
+ out_dir = get_output_dir(settings)
223
+ out_dir.mkdir(parents=True, exist_ok=True)
224
+
225
+ puzzle.save(out_dir / f"{settings['output_basename']}.png",
226
+ dpi=(settings["dpi"], settings["dpi"]))
227
+ key.save(out_dir / f"{settings['output_basename']}_key.png",
228
+ dpi=(settings["dpi"], settings["dpi"]))
229
+
230
+ print("Saved puzzle and key.")
231
+
232
+
233
+ # =========================
234
+ # EXAMPLE
235
+ # =========================