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

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

generate_levels.py337 lines · 14.0 KiBRaw
1import random
2import os
3from collections import Counter
4
5class LevelGenerator:
6 def __init__(self, word_list):
7 self.word_list = [w.strip().upper() for w in word_list]
8 self.word_index = {w: i for i, w in enumerate(self.word_list)}
9
10 def generate_level(self, level):
11 # Determine target difficulty index
12 base_offset = (level - 800) * 45
13 rows, cols = 11, 11
14
15 # Pick a target wheel word (7-8 letters)
16 wheel_candidates = [w for w in self.word_list[base_offset:base_offset+10000] if 7 <= len(w) <= 8]
17 if not wheel_candidates:
18 wheel_candidates = [w for w in self.word_list[max(0, len(self.word_list)-10000):] if 7 <= len(w) <= 8]
19 if not wheel_candidates:
20 wheel_candidates = [w for w in self.word_list if 7 <= len(w) <= 8]
21
22 for _ in range(300):
23 wheel_word = random.choice(wheel_candidates)
24 wheel_counts = Counter(wheel_word)
25
26 candidates = []
27 for w in self.word_list:
28 if 3 <= len(w) <= 8:
29 w_counts = Counter(w)
30 if all(w_counts[c] <= wheel_counts[c] for c in w_counts):
31 candidates.append(w)
32
33 if len(candidates) < 6:
34 continue
35
36 # Difficulty scoring - favor words near base_offset
37 def difficulty_score(w):
38 idx = self.word_index.get(w, -1)
39 # Penalize unknown or very common words for high levels
40 if idx < 0 or idx < base_offset // 2: return 999999
41 return abs(idx - base_offset)
42
43 candidates.sort(key=difficulty_score)
44 other_candidates = candidates[:50]
45
46 for _ in range(200):
47 grid = [[' ' for _ in range(cols)] for _ in range(rows)]
48
49 # Determine mandatory words
50 mandatory = [wheel_word]
51 include_second_long = random.random() < 0.5
52 if include_second_long:
53 long_candidates = [w for w in candidates if 6 <= len(w) <= 8 and w != wheel_word]
54 if long_candidates:
55 mandatory.append(random.choice(long_candidates[:10]))
56
57 random.shuffle(other_candidates)
58 words_to_try = mandatory + [w for w in other_candidates if w not in mandatory]
59 words_to_try = words_to_try[:15]
60
61 placed_words = []
62 if self.place_words(grid, words_to_try, placed_words, rows, cols):
63 if level % 3 == 0:
64 self.add_disconnected_word(grid, candidates, placed_words, rows, cols)
65
66 min_words = min(8, 5 + (level - 862) // 300)
67 # Check mandatory words were actually placed
68 if len(placed_words) >= min_words and all(w in placed_words for w in mandatory):
69 wheel = self.get_wheel_letters(placed_words)
70 distinct_letters = len(set(wheel))
71 total_letters = len(wheel)
72
73 # Minimums scale with level
74 min_distinct = max(4, min(6, 4 + (level - 862) // 500))
75 min_total = max(5, min(8, 5 + (level - 862) // 400))
76
77 if total_letters <= 8 and distinct_letters >= min_distinct and total_letters >= min_total:
78 return self.grid_to_string(grid)
79
80 return "ERROR\nLEVEL"
81
82 def get_wheel_letters(self, words):
83 max_counts = {}
84 for word in words:
85 counts = {}
86 for char in word:
87 counts[char] = counts.get(char, 0) + 1
88 for char, count in counts.items():
89 max_counts[char] = max(max_counts.get(char, 0), count)
90
91 wheel = []
92 for char, count in max_counts.items():
93 wheel.extend([char] * count)
94 return wheel
95
96 def place_words(self, grid, words, placed, rows, cols):
97 if not words: return True
98 # Sort words to place longest first
99 words_sorted = sorted(words, key=len, reverse=True)
100 first_word = words_sorted[0]
101
102 if self.place_first_word(grid, first_word, rows, cols):
103 placed.append(first_word)
104 for i in range(1, len(words_sorted)):
105 word = words_sorted[i]
106 if self.try_place_intersecting(grid, word, placed, rows, cols):
107 placed.append(word)
108 if len(placed) >= 12: break
109 return len(placed) >= 4
110 return False
111
112 def place_first_word(self, grid, word, rows, cols):
113 horizontal = random.choice([True, False])
114 r = random.randint(rows // 4, rows // 2)
115 c = random.randint(cols // 4, cols // 2)
116 if self.can_place(grid, word, r, c, horizontal, rows, cols):
117 self.do_place(grid, word, r, c, horizontal)
118 return True
119 return False
120
121 def try_place_intersecting(self, grid, word, placed, rows, cols):
122 possible_placements = []
123 for r in range(rows):
124 for c in range(cols):
125 if self.can_place(grid, word, r, c, True, rows, cols) and self.intersects(grid, word, r, c, True):
126 possible_placements.append((r, c, True))
127 if self.can_place(grid, word, r, c, False, rows, cols) and self.intersects(grid, word, r, c, False):
128 possible_placements.append((r, c, False))
129
130 if possible_placements:
131 r, c, horizontal = random.choice(possible_placements)
132 self.do_place(grid, word, r, c, horizontal)
133 return True
134 return False
135
136 def add_disconnected_word(self, grid, all_candidates, placed_words, rows, cols):
137 available = [w for w in all_candidates if w not in placed_words]
138 if not available: return
139
140 # Calculate current bounds
141 min_r, max_r = rows, -1
142 min_c, max_c = cols, -1
143 for r in range(rows):
144 for c in range(cols):
145 if grid[r][c] != ' ':
146 min_r = min(min_r, r)
147 max_r = max(max_r, r)
148 min_c = min(min_c, c)
149 max_c = max(max_c, c)
150
151 if max_r == -1: return
152
153 random.shuffle(available)
154 for word in available[:20]:
155 # Try placing above or below with exactly 1 row gap
156 possible_placements = []
157
158 # Above
159 target_r = min_r - 2
160 if target_r >= 0:
161 for c in range(cols - len(word) + 1):
162 if self.can_place(grid, word, target_r, c, True, rows, cols, isolated=True):
163 possible_placements.append((target_r, c))
164
165 # Below
166 target_r = max_r + 2
167 if target_r < rows:
168 for c in range(cols - len(word) + 1):
169 if self.can_place(grid, word, target_r, c, True, rows, cols, isolated=True):
170 possible_placements.append((target_r, c))
171
172 if possible_placements:
173 r, c = random.choice(possible_placements)
174 self.do_place(grid, word, r, c, True)
175 placed_words.append(word)
176 return
177
178 def can_place(self, grid, word, r, c, horizontal, rows, cols, isolated=False):
179 if horizontal:
180 if c + len(word) > cols: return False
181 for i in range(len(word)):
182 char = grid[r][c + i]
183 if char != ' ' and char != word[i]: return False
184 if char == ' ':
185 if not self.check_neighbors(grid, r, c + i, horizontal, word[i], rows, cols): return False
186 if c > 0 and grid[r][c - 1] != ' ': return False
187 if c + len(word) < cols and grid[r][c + len(word)] != ' ': return False
188 else:
189 if r + len(word) > rows: return False
190 for i in range(len(word)):
191 char = grid[r + i][c]
192 if char != ' ' and char != word[i]: return False
193 if char == ' ':
194 if not self.check_neighbors(grid, r + i, c, horizontal, word[i], rows, cols): return False
195 if r > 0 and grid[r - 1][c] != ' ': return False
196 if r + len(word) < rows and grid[r + len(word)][c] != ' ': return False
197
198 if isolated:
199 for i in range(len(word)):
200 curr_r = r if horizontal else r + i
201 curr_c = c + i if horizontal else c
202 if self.has_any_neighbor(grid, curr_r, curr_c, rows, cols): return False
203 return True
204
205 def check_neighbors(self, grid, r, c, horizontal, char, rows, cols):
206 if horizontal:
207 if r > 0 and grid[r - 1][c] != ' ': return False
208 if r < rows - 1 and grid[r + 1][c] != ' ': return False
209 else:
210 if c > 0 and grid[r][c - 1] != ' ': return False
211 if c < cols - 1 and grid[r][c + 1] != ' ': return False
212 return True
213
214 def has_any_neighbor(self, grid, r, c, rows, cols):
215 dr = [-1, 1, 0, 0]
216 dc = [0, 0, -1, 1]
217 for i in range(4):
218 nr, nc = r + dr[i], c + dc[i]
219 if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] != ' ':
220 return True
221 return False
222
223 def intersects(self, grid, word, r, c, horizontal):
224 for i in range(len(word)):
225 curr_r = r if horizontal else r + i
226 curr_c = c + i if horizontal else c
227 if grid[curr_r][curr_c] == word[i]: return True
228 return False
229
230 def do_place(self, grid, word, r, c, horizontal):
231 for i in range(len(word)):
232 if horizontal: grid[r][c + i] = word[i]
233 else: grid[r + i][c] = word[i]
234
235 def grid_to_string(self, grid):
236 # 1. Find the bounds of the actual letters
237 rows = len(grid)
238 cols = len(grid[0])
239 min_r, max_r = rows, -1
240 min_c, max_c = cols, -1
241
242 for r in range(rows):
243 for c in range(cols):
244 if grid[r][c] != ' ':
245 min_r = min(min_r, r)
246 max_r = max(max_r, r)
247 min_c = min(min_c, c)
248 max_c = max(max_c, c)
249
250 if max_r == -1: return ""
251
252 # 2. Extract the subgrid
253 trimmed_rows = []
254 for r in range(min_r, max_r + 1):
255 row_str = "".join(grid[r][min_c : max_c + 1])
256 trimmed_rows.append(row_str)
257
258 return "\n".join(trimmed_rows)
259
260if __name__ == "__main__":
261 script_dir = os.path.dirname(os.path.abspath(__file__))
262
263 # Load common words and unique them while preserving order
264 with open(os.path.join(script_dir, "common_words_list.txt"), "r") as f:
265 raw_words = [w.strip().upper() for w in f.readlines()]
266 words = []
267 seen = set()
268 for w in raw_words:
269 if w.isalpha() and w not in seen:
270 words.append(w)
271 seen.add(w)
272
273 # Load bad words with "good Christian family" filtering:
274 # - Exact matches always blocked (any length, e.g. DAMN, HELL, FRIGGING, NIGGAH, ASS, SEX)
275 # - Substring blocked for severe slurs len>=4 (NIGGAH contains NIGGA, COONSKIN contains COON)
276 # but NOT for swear-adjacent euphemisms where innocent embedding is common:
277 # FRIG in REFRIGERATOR, HELL in SHELL, CRAP in SCRAP, DARN/DANG in DANGER, HECK in CHECK, etc.
278 # Those Christian words are exact-only.
279 # - For 3-letter, only unambiguous blocked as substrings (FAG, BBW, XXX), while
280 # ASS/TIT/SEX/CUM allowed as substring because CLASS, TITLE, CUMIN are innocent.
281 try:
282 with open(os.path.join(script_dir, "bad-words.txt"), "r") as f:
283 raw_bad = [w.strip().upper() for w in f.readlines() if w.strip()]
284 bad_words = set(raw_bad)
285
286 # Words that should be blocked ONLY as exact matches, not as substrings,
287 # because they appear inside innocent words (HELL in SHELL, FRIG in REFRIGERATOR, etc)
288 CHRISTIAN_EXACT_ONLY = {
289 "FRIGGING","FRIGGIN","FRIGGED","FRIG","FRIKKIN","FRIKKING","FRICKING","FRICKIN","FRICK",
290 "FECKING","FECKIN","FECK","FREAKING","FREAKIN",
291 "DAMN","DAMNED","DAMNING","DAMNABLY","DAMNDEST","DAMMIT","GODDAMN","GODDAMNED","GODDAM",
292 "HELL","HELLS","HELLISH",
293 "CRAP","CRAPPY","CRAPPER",
294 "PISS","PISSED","PISSER","PISSING","PISSY",
295 "DARN","DARNED","DARNDEST","DANG","DANGED",
296 "HECK","HECKLE","HECKLING","HECKLED","HECKLER",
297 "BLOODY","BLOODILY",
298 }
299 COMMON_SENSE_INNOCENT_3 = {"ASS", "TIT", "SEX", "CUM"}
300
301 bad_substrings = []
302 for b in raw_bad:
303 if not b.isalpha():
304 continue
305 if b in CHRISTIAN_EXACT_ONLY:
306 continue # exact-only
307 if len(b) >= 4:
308 bad_substrings.append(b)
309 elif len(b) == 3 and b not in COMMON_SENSE_INNOCENT_3:
310 bad_substrings.append(b)
311 except FileNotFoundError:
312 bad_words = set()
313 bad_substrings = []
314
315 def contains_bad_substring(word: str) -> bool:
316 if word in bad_words:
317 return True
318 for bad in bad_substrings:
319 if bad in word:
320 return True
321 return False
322
323 words = [w for w in words if not contains_bad_substring(w)]
324
325 generator = LevelGenerator(words)
326
327 # Output path relative to scripts/wordmaker/
328 output_dir = os.path.join(script_dir, "../../games/wordmaker/src/main/assets/levels")
329 os.makedirs(output_dir, exist_ok=True)
330
331 for level in range(2001, 8001):
332 if level % 100 == 0:
333 print(f"Generating level {level}...")
334 grid_str = generator.generate_level(level)
335 with open(os.path.join(output_dir, f"{level}.txt"), "w") as f:
336 f.write(grid_str)
337 print("Done!")