我制作了一个脚本,使用递归回溯将迷宫创建为矩阵。我选择一个随机方向移动,并检查是否已经有路径或迷宫边界。我的脚本工作正常,但是太复杂了,我不太喜欢。但是我不知道如何修改它以使其更优雅。
while len(paths) < all_positions: # while maze has unvisited areas (not all 'cells' connected to each other)
if len(directions) == 0: # if we can't move anyway (blocked)
row, col = random.choice(paths) # pick a random cell on a path
directions = ['up', 'down', 'left', 'right']
else:
direction = random.choice(directions) # pick a random direction
if direction == 'up':
if row-2 > 0 and pixels[row-2, col, 0] != 255: # check a 'cell' to not move outside the maze AND check to not connect to a 'cell' that is already in path (not to make a loop)
row -= 2
dig(row+1, col) # add a 'cell' between the current one and the next one to a path
dig(row, col) # add the next 'cell' to a path
directions = ['up', 'down', 'left', 'right'] # now we can't pick any direction again
paths.append([row, col]) # append the 'cell' to a list of path cells
else:
directions.remove(direction) # if we can't move the picked direction, the delete this direction from available directions
if direction == 'down':
if row+2 <= height-2 and pixels[row+2, col, 0] != 255:
row += 2
dig(row-1, col)
dig(row, col)
directions = ['up', 'down', 'left', 'right']
paths.append([row, col])
else:
directions.remove(direction)
if direction == 'left':
if col-2 > 0 and pixels[row, col-2, 0] != 255:
col -= 2
dig(row, col+1)
dig(row, col)
directions = ['up', 'down', 'left', 'right']
paths.append([row, col])
else:
directions.remove(direction)
if direction == 'right':
if col+2 <= width-2 and pixels[row, col+2, 0] != 255:
col += 2
dig(row, col-1)
dig(row, col)
directions = ['up', 'down', 'left', 'right']
paths.append([row, col])
else:
directions.remove(direction)