提问人:Hassan Usman 提问时间:11/14/2023 最后编辑:Hassan Usman 更新时间:11/14/2023 访问量:53
如何生成一个没有死胡同的迷宫?[关闭]
How do I generate a maze without dead ends? [closed]
问:
这个程序开发了一个迷宫,它的路径我希望迷宫没有死胡同,但我做不到,我尝试过,但它归档了整个迷宫,没有留下路径的空间。有人可以帮我吗?? 以下是生成迷宫及其路径的代码:
import turtle
import random
cell_size = 10
def generate_maze(width, height):
maze = [['-'] * (2 * width + 1) for _ in range(2 * height + 1)]
def carve(x, y):
directions = [(2, 0), (-2, 0), (0, 2), (0, -2)]
random.shuffle(directions)
for dx, dy in directions:
nx, ny = x + dx, y + dy
if 0 < nx < 2 * width and 0 < ny < 2 * height and maze[ny][nx] == '-':
maze[ny][nx] = ' '
maze[y + dy // 2][x + dx // 2] = ' '
carve(nx, ny)
start_x, start_y = 1, 2 * height - 1
end_x, end_y = width * 2 - 1, 1
maze[start_y][start_x] = ' '
carve(start_x, start_y)
return maze
def draw_maze_with_turtle(maze):
turtle.speed(0)
turtle.hideturtle()
turtle.bgcolor('black')
turtle.color('white')
for y, row in enumerate(maze):
for x, cell in enumerate(row):
if cell == '-':
turtle.penup()
turtle.goto(x * cell_size - width * cell_size, height * cell_size - y * cell_size)
turtle.pendown()
turtle.forward(cell_size)
turtle.right(90)
turtle.forward(cell_size)
turtle.right(90)
turtle.forward(cell_size)
turtle.right(90)
turtle.forward(cell_size)
turtle.right(90)
def solve_maze(maze, start, end):
stack = [start]
visited = set()
visited = set(stack)
while stack:
x, y = stack[-1]
if (x, y) == end:
break
found = False
for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
nx, ny = x + dx, y + dy
if 0 <= nx < 2 * width and 0 <= ny < 2 * height and maze[ny][nx] == ' ' and (nx, ny) not in visited:
visited.add((nx, ny))
stack.append((nx, ny))
found = True
break
if not found:
stack.pop()
return stack
def draw_path_with_turtle(path):
turtle.pencolor('green')
turtle.pensize(3)
for x, y in path:
turtle.penup()
turtle.goto(x * cell_size - width * cell_size + cell_size / 2 , height * cell_size - y * cell_size - cell_size / 2 )
turtle.pendown()
turtle.dot(cell_size - 2)
if __name__ == '__main__':
width = 60
height = 5
maze = generate_maze(width, height)
start_x, start_y = 1, 2 * height - 1
maze[start_y][start_x] = ' '
draw_maze_with_turtle(maze)
start = (start_x, start_y)
end = (width * 2 - 1, 1)
path = solve_maze(maze, start, end)
draw_path_with_turtle(path)
turtle.delay(0)
turtle.done()
生成没有死胡同的迷宫的解决方案。
答: 暂无答案
评论