Schleife über Wörtern < /p>
Verwenden Sie boolean Word_good < /code>, um zu verfolgen, ob die Wörter zum Gitter hinzugefügt werden können. DIRECTION_GOOD , um zu überprüfen, ob eine Dimension für dieses Wort geeignet war. Wenn falsch, sucht es weiter. Wenn wahr, macht es wort_good true. Wenn falsch, sucht es weiter. Wenn es wahr bleibt, macht es Direction_Good true. Irgendwelche Ideen? < /P>
Hier ist der Code: < /p>
Code: Select all
from random import choice, shuffle
from string import ascii_lowercase
import re
def generate_wordsearch(words: list[str]):
grid = [["_" for i in range(10)] for j in range(10)]
for word in words:
if len(word) > 10: continue # skip if word is longer than grid
word = word.lower()
directions = ["right", "down", "across"]
word_good = False
for direction in directions:
direction_good = False
max_x = max_y = dx = dy = 0
if direction == "right":
max_x = 10 - len(word)
max_y = 10
dx = 1
elif direction == "down":
max_x = 10
max_y = 10 - len(word)
dy = 1
else:
max_x = 10 - len(word)
max_y = max_x
dx = 1
dy = 1
open_coords = [(x, y) for x in range(max_x) for y in range(max_y)]
while bool(open_coords):
pos = choice(open_coords)
position_good = True
for i in range(len(word)):
x = pos[0] + dx*i
y = pos[1] + dy*i
if grid[y][x] != "_" and grid[y][x] != word[i]:
position_good = False
break
if position_good:
direction_good = True
for i in range(len(word)):
x = pos[0] + dx*i
y = pos[1] + dy*i
grid[y][x] = word[i]
break
else:
open_coords.remove(pos)
if direction_good:
included_words.append(word)
word_good = True
break
else:
directions.pop(0)
if not word_good:
excluded_words.append(word)
return (grid, included_words, excluded_words)