单词狩猎生成器递归放置单词函数异常问题排查
单词狩猎(Wordhunt)生成器问题修复
我开发了一个单词狩猎生成器,需要在矩阵随机位置水平放置单词"GAME",替换'x'且不能与已有的'W'重叠。但代码有时会生成错误结果,比如单词部分覆盖'W'的位置,或者出现不完整的单词放置。
正确示例:
x G A M E x x x W x x x x x x W x x x x x x W x x x x x x W x x x x x x
错误示例:
x x x x x x x x W x x x x G A W E x x x x x W x x x x x x W x x x x x x
我的代码如下:
from random import randint word = 'GAME' def place_word(): wordhunt = [['x', 'x', 'x', 'x', 'x', 'x'], ['x', 'x', 'W', 'x', 'x', 'x'], ['x', 'x', 'x', 'W', 'x', 'x'], ['x', 'x', 'x', 'x', 'W', 'x'], ['x', 'x', 'x', 'x', 'x', 'W'], ['x', 'x', 'x', 'x', 'x', 'x']] #generate the initial position of the word on the matrix line = randint(0, 5) column = randint(0, 2) #iterator to place the new letters for i in range(0,4,1): #Check if the position is allowed if wordhunt[line][column+i] == 'x': wordhunt[line][column+i] = word[i] #if i reaches 3 the placement is complete if i == 3: return wordhunt #if it tries to place a letter on a forbidden position, it runs the function again else: place_word() new_wordhunt = place_word() for i in range(0, 6, 1): for j in range(0, 6, 1): print(new_wordhunt[i][j], end=' ') print()
问题分析
你的代码存在两个核心问题:
- 递归调用未返回结果,原循环继续执行:当检测到某个位置是'W'时,你调用了
place_word()但没有return这个递归的结果,原函数的循环会继续执行后续的i值,把单词剩余的字母强行放到当前行的位置,导致出现部分单词和'W'共存的错误。 - 边放置边检查的逻辑漏洞:逐个字母放置时,前面的字母成功放置后,后面遇到'W'触发递归,但原矩阵已经被修改,而递归生成的正确矩阵没有被返回,最终返回的是被部分修改的错误矩阵。
修复方案
优化逻辑,先检查整个单词的放置区域是否合法,再一次性放置,同时确保递归调用正确返回结果:
from random import randint word = 'GAME' word_length = len(word) matrix_size = 6 def place_word(): # 每次调用都创建新矩阵 wordhunt = [['x', 'x', 'x', 'x', 'x', 'x'], ['x', 'x', 'W', 'x', 'x', 'x'], ['x', 'x', 'x', 'W', 'x', 'x'], ['x', 'x', 'x', 'x', 'W', 'x'], ['x', 'x', 'x', 'x', 'x', 'W'], ['x', 'x', 'x', 'x', 'x', 'x']] line = randint(0, matrix_size - 1) # 确保单词不会超出矩阵边界 column = randint(0, matrix_size - word_length) # 先检查整个单词位置是否都是'x' valid = True for i in range(word_length): if wordhunt[line][column + i] != 'x': valid = False break if valid: # 合法则放置整个单词 for i in range(word_length): wordhunt[line][column + i] = word[i] return wordhunt else: # 不合法则递归重试,必须返回递归结果 return place_word() new_wordhunt = place_word() for row in new_wordhunt: print(' '.join(row))
修复说明
- 先检查单词要放置的所有位置是否都是'x',从根源避免部分放置的问题。
- 递归调用时返回
place_word()的结果,确保最终返回的是完全合法的矩阵。 - 使用
matrix_size和word_length常量,让代码更易维护,后续修改单词长度或矩阵大小无需多处调整。 - 打印部分简化为遍历每行并用
join输出,代码更简洁易读。
修改后,代码会一直重试直到找到合法位置,保证生成的结果始终符合要求。
内容的提问来源于stack exchange,提问作者Diogo Gonçalves
相关产品推荐
相关产品推荐

