Python构建单词搜索生成器时单词无法完整显示在网格的问题
问题定位
你的代码存在两处核心问题:
return grid语句缩进错误,当前嵌套在for循环内部,循环仅执行1次(只写入第一个字母)就直接返回网格,剩余单词字母根本没有执行写入逻辑- 变量命名存在歧义,函数参数
words实际接收的是单个单词,容易和单词列表概念混淆(不影响运行,但不便于后续迭代维护)
修复后的完整代码
import string import random width = 10 height = 10 # 函数参数改为word,明确是单个单词 def place_word(word, grid): # 随机选择正序/倒序放置 word = random.choice([word, word[::-1]]) # 随机选择方向:水平向右/垂直向下/右下斜向 direction = random.choice([[1,0], [0,1], [1,1]]) # 计算起始坐标的合法范围 x_max = width if direction[0] == 0 else width - len(word) y_max = height if direction[1] == 0 else height - len(word) x = random.randrange(0, x_max) y = random.randrange(0, y_max) print(f"单词起始坐标:[{x}, {y}]") # 循环写入所有字母 for i in range(len(word)): grid[y + direction[1]*i][x + direction[0]*i] = word[i] # return 移到for循环外层,全部写入完成后再返回 return grid # 生成初始网格 grid = [[random.choice(string.ascii_uppercase) for _ in range(width)] for _ in range(height)] # 放置单词 for word in ["HELLO"]: place_word(word, grid) # 打印网格 print("\n".join(map(lambda row: " ".join(row), grid)))
修复验证
运行修复后的代码,HELLO会完整按照随机选择的方向写入网格,多次运行可观察不同方向的放置效果。如果后续需要支持多个单词放置,只需在单词列表中添加对应单词即可。
内容的提问来源于stack exchange,提问作者Gimlore
相关产品推荐
相关产品推荐

