我的数组中只有一个项目正在使用(应该全部使用)



这个程序应该使用随机字母和数组中的5个单词进行单词搜索。该程序只使用数组中的一个字,但应该使用所有5个字。这是我的密码。

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)
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()

我还想补充一点,我有一个版本只使用控制台(没有tkinter(,它使用数组中的所有单词;如果有帮助的话,我可以发布。

在我看来,您只是搞砸了缩进。CCD_ 1最后一次被用于双线CCD_ 2环路CCD_。在我看来,线路while not placed:和许多后续线路应该是环路主体的一部分。

这有道理吗?我没有试过。

最新更新