我有一个函数(称为generateMaze),该函数应该生成一个迷宫,但到目前为止,我只是让它找到了网格中的每个“单元”。当找到该单元格时,会将其标记为“已访问”。我用黑色圆圈标记每个单元格,但“访问”后应将其标记为绿色。当我运行程序时,所有内容立即变为绿色。我想在generateMaze函数的末尾添加一个睡眠,这样我可以看到单元变绿的过程是发生的,而不是立即发生的。在该函数中,它会打印“ Len:{len(openCells)}”,它会打印允许进入的单元格数量。如果我在函数中的任何地方添加了睡眠,它将开始打印出超出可能的最大值4的数字。
# Function
def generateMaze(x=40, y=40):
global cells
possiblePositions = []
openCells = []
# These are all the possible positions that we can go to
possiblePositions.append([x-80, y])
possiblePositions.append([x+80, y])
possiblePositions.append([x, y-80])
possiblePositions.append([x, y+80])
# Find open cells using the possiblePositions
for cell in cells:
for i in range(len(possiblePositions)):
if cell.x == possiblePositions[i][0] and cell.y == possiblePositions[i][1] and (not cell.visited()):
openCells.append(cell)
# Choose random cell
print("Len: ", len(openCells))
if len(openCells) > 0:
targetCell = openCells[randint(0, len(openCells)-1)]
if targetCell in cells:
cells[cells.index(targetCell)].visit()
else:
print("Error: Could not find targetCell in cells")
generateMaze(targetCell.x, targetCell.y)
else:
print("Done generating")
#mainloop
while not done:
# [...]
if shouldGenMaze:
shouldGenMaze = False
print("Generating Maze...")
x = threading.Thread(target = generateMaze)
x.start()
# [...]
答案 0 :(得分:0)
该代码对我有用。也许这与您的线程有关,仅使用单个函数就很难说。
很显然,如果将延迟放在函数末尾,则只会产生一个很大的递归尾部延迟。
这是我的MRE:
import random
import time
cells = []
class Cell:
def __init__( self, x, y ):
self.x = x
self.y = y
self.been_there = False
def visited( self ):
return self.been_there
def visit( self ):
self.been_there = True
def generateMaze(x=40, y=40):
global cells
possiblePositions = []
openCells = []
# These are all the possible positions that we can go to
possiblePositions.append([x-80, y])
possiblePositions.append([x+80, y])
possiblePositions.append([x, y-80])
possiblePositions.append([x, y+80])
# Find open cells using the possiblePositions
for cell in cells:
for i in range(len(possiblePositions)):
if cell.x == possiblePositions[i][0] and cell.y == possiblePositions[i][1] and (not cell.visited()):
openCells.append(cell)
# Choose random cell
print("Len: ", len(openCells))
if len(openCells) > 0:
targetCell = openCells[random.randint(0, len(openCells)-1)]
if targetCell in cells:
cells[cells.index(targetCell)].visit()
else:
print("Error: Could not find targetCell in cells")
time.sleep( 1 )
generateMaze(targetCell.x, targetCell.y)
else:
print("Done generating")
SIZE=121 #?
for y in range( 0, SIZE ):
for x in range( 0, SIZE ):
cells.append( Cell( x, y ) )
generateMaze()