【发布时间】:2021-12-11 06:38:01
【问题描述】:
我正在 Python 中创建一个单词搜索生成器,但是我遇到了出现在网格中的单词的问题。制作网格时,其中一个字母的坐标在那里,但不是整个单词。我不确定哪些部分出了问题,任何帮助将不胜感激
import string
import random
width = 10
height = 10
def place_words(words, grid):
words = random.choice([words, words[::-1]])
direction = random.choice([[1,0], [0,1], [1,1]])
xstart = width if direction[0] == 0 else width - len(words)
ystart = height if direction[1] == 0 else height - len(words)
x = random.randrange(0, xstart)
y = random.randrange(0, ystart)
print([x, y])
for i in range(0, len(words)):
grid[y + direction[1]*i][x + direction[0]*i] = words[i]
return grid
grid = [[random.choice(string.ascii_uppercase) for i in range(0, width)]
for j in range(0, height)]
for words in ["HELLO"]:
place_words(words, grid)
print("\n".join(map(lambda row: " ".join(row), grid)))
这是它的结果,你可以看到这个词不存在!
[3, 0]
R J E O K S Y U Q F
T E P U N B Y Z I O
J A Y N F D S V T Y
H G A M R W O T I M
O W J Q R G Q E D Q
W D J R T N N N Q N
K Z B X H V U Y J X
J F P D W F I C W U
C Z V B Q C Z R K X
E J A K R N J V S Y
【问题讨论】:
-
这可能是巧合/很好,因为您的网格宽度和高度值是相同的;你能解释一下为什么
xstart和ystart的值表达式是完全相同的表达式吗? -
您能解释一下您希望
words = random.choice([words, words[::-1]])做什么吗?它采用列表words和反向列表words[::-1];我怀疑您打算将words列表和单独反转的单词元素列表[word[::-1] for word in words] -
@JoshuaVoskamp 是的,我刚刚意识到 x 和 y,我已经更改了 y,以便它改为 ystart = height if direction[1] == 0 else height - len(words)跨度>
-
@JoshuaVoskamp 是的,我不知道如何得到单词中的每个字母,我认为这可能与此有关,但我不确定如何更改它以更正它
标签: python python-3.x puzzle wordsearch