我正在尝试实现一些代码,该代码在数组中带有一些单词的情况下运行搜索游戏生成器,因此我决定使用在视频中经过测试的一些代码,该视频似乎正常运行,但是当我运行时它冻结的代码,所以我想知道发生了什么:
这是我正在谈论的代码:
import random
import string
words = ['PYTHON', 'ROBBIE', 'GITHUB', 'BEEF']
grid_size=15
grid = [['_' for _ in range(grid_size)] for _ in range(grid_size)]
orientations = ['leftright','updown','diagonalup','diagonaldown']
#Prints the grid
def print_grid():
for x in range(grid_size):
print('\t'*5+' '.join(grid[x]))
#Generates grid
def generategrid(words):
for word in words:
word_length = len(word)
placed = False
while not placed:
orientation = random.choice(orientations)
#Sets orientation given by a random number
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
#We generate a random starting point, then we calculate the ending point and if it exceeds the limit, we calculate the number again
x_position = random.randint(0,grid_size)
y_position = random.randint(0,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
#we set the word on the previously given position
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 there is some character that could be used to form the word
if character_at_new_position != '_':
if character_at_new_position == character:
continue
else:
failed = True
break
if failed:#We do the process from above again until we can put the word on the grid
continue
else:
#Everything worked perfectly and the word was placed without problems
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
placed = True
generategrid(words)
print_grid()
当我运行该程序时,它冻结了,但是在视频中,此代码似乎运行良好。任何建议或观察将不胜感激!
答案 0 :(得分:0)
在while not placed:
之后,您有一个无限循环。我不确定代码的意图是什么,但是我认为您的意思是在一段时间后设置placed = True
。
在代码中进一步做到这一点,所以我的猜测是一个缩进错误。在Python中,缩进定义了循环的范围,因此请在您正在查看的示例中仔细检查缩进。