我在尝试制作单词搜索难题生成器时遇到了问题,全天遇到了多个问题。 (由于这个社区,我解决了大多数问题!)
我现在有另一个问题,我有一个循环,应该找到一个位置来放置一个单词,将其放置,然后继续下一个单词。取而代之的是找到单词可能存在的所有可能位置,并将单词放置在所有可能的位置。我只希望每个字出现一次。我以为while not placed
和placed = true
行可以处理此问题,但无法正常工作。
感谢您的任何帮助,这是我的代码:
import tkinter as tk
import random
import string
handle = open('dictionary.txt')
words = handle.readlines()
handle.close()
grid_size = 10
words = [ random.choice(words).upper().strip() \
for _ in range(5) ]
print ("The words are:")
print(words)
grid = [ [ '_' for _ in range(grid_size) ] for _ in range(grid_size) ]
orientations = [ 'leftright', 'updown', 'diagonalup', 'diagonaldown' ]
class Label(tk.Label):
def __init__(self, parent, **kwargs):
super().__init__(parent, **kwargs, font=("Courier", 44))
#self.bind('<Button-1>', self.on_click)
#def on_click(self, event):
#w = event.widget
#row, column = w.grid_info().get('row'), w.grid_info().get('column')
#print('coord:{}'.format((row, column)))
#w.destroy()
class App(tk.Tk):
def __init__(self):
super().__init__()
for row in range(grid_size):
for column in range(grid_size):
for word in words:
word_length = len(word)
placed = False
while not placed:
orientation = random.choice(orientations)
if orientation == 'leftright':
step_x = 1
step_y = 0
if orientation == 'updown':
step_x = 0
step_y = 1
if orientation == 'diagonalup':
step_x = 1
step_y = -1
if orientation == 'diagonaldown':
step_x = 1
step_y = 1
x_position = random.randrange(grid_size)
y_position = random.randrange(grid_size)
ending_x = x_position + word_length*step_x
ending_y = y_position + word_length*step_y
if ending_x < 0 or ending_x >= grid_size: continue
if ending_y < 0 or ending_y >= grid_size: continue
failed = False
for i in range(word_length):
character = word[i]
new_position_x = x_position + i*step_x
new_position_y = y_position + i*step_y
character_at_new_position = grid[new_position_x][new_position_y]
if character_at_new_position != '_':
if character_at_new_position == character:
continue
else:
failed = True
break
if failed:
continue
else:
for i in range(word_length):
character = word[i]
new_position_x = x_position + i*step_x
new_position_y = y_position + i*step_y
grid[new_position_x][new_position_y] = character
if ( grid[row][column] == grid[new_position_x][new_position_y] ):
grid[row][column] = grid[new_position_x][new_position_y]
Label(self, text=character).grid(row=row, column=column)
placed = True
#if ( grid[row][column] == '_' ):
#txt = random.SystemRandom().choice(string.ascii_uppercase)
#Label(self, text=txt).grid(row=row, column=column)
if __name__ == '__main__':
App().mainloop()
我可以向您保证,您对while
循环的期望是正确的。
In [1]: placed = False
In [2]: i = 0
In [3]: while not placed:
...: i += 1
...: print(i)
...: if i == 5:
...: placed = True
...:
1
2
3
4
5
[给我,我怀疑您的代码总是命中continue
,这意味着它从未命中过语句placed = True
,因此无限循环。因此,我建议您检查continue
的条件是否符合预期。
希望这会有所帮助!