我正在尝试使用给定单词列表制作单词搜索网格。我的问题是某些单词显示不正确。
我已经更新了代码,见下文
我已尝试修复以前的错误,但现在我遇到了无法修复的超出范围错误,如果有人可以提供帮助,我将不胜感激
注1:我没有包含所有的程序功能,如果需要我会在稍后包含它们
该程序接受一个像这样的文本文件:
9 9 white black blue green pink yellow red grey purple
其中文件中的前 2 个数字是网格的尺寸,其余的是要放置在网格中的单词。
import random
import string
fi=input('Insert the entry file name(entry.txt): ')
fo=input('Insert the exit file name(.txt): ')
grid_size=[]
words=[]
matrix=[]
def read_file(storage):
file=open(storage)
n=file.readline()
lista=n.split()
lista=list(map(int,lista)) #sets the size of the grid
for i in lista:
grid_size.append(i)
for line in file:
line=line.replace("\n","")
words.append(line)
file.close()
def grid_generator(grid_size):
n, p = grid_size
for i in range(n):
matriz.append([])
for j in range(p):
matriz[i].append(".")
def sets_word_inside(grid_size, word, grid):
n, p = grid_size
word = random.choice([word,word[::-1]])
#horizontal,vertical,diagonal
d = random.choice([[1,0],[0,1],[1,1]])
xsize = n if d[0] == 0 else n - len(word)
ysize = p if d[1] == 0 else p - len(word)
x= random.randrange(0,xsize)
y= random.randrange(0,ytsize) #position
for i, letter in enumerate(word):
char = grid[y+d[1]*i][x+d[0]*i]
if char != " " and char != letter:
# If it reaches an already filled space - restart the process.
# The second condition allow the words that cross with repeated words are created.
return False
grid[y+d[1]*i][x+d[0]*i] = letter[i]
return True
现在代码的输出是这样的:
9
white
black
blue
green
pink
yellow
red
grey
purple
p w b i t y l d i
p v w o l e e y t
x g a x j r i m g
q i c j b g j e x
s s k g q l g r r
p i n k i o u t r
e l p r u p g e o
l a b l s r p g y
c o r y e u f r x