python迷宫画图
时间: 2025-01-09 08:00:50 浏览: 63
### 使用Python绘制迷宫图形
为了创建一个迷宫并将其可视化,可以采用`matplotlib.pyplot`来绘图。然而,在这里更推荐使用`turtle`库,因为其简单易懂且适合初学者学习基本的图形编程概念[^1]。
下面展示一段基于`turtle`模块编写的用于生成随机迷宫以及显示该迷宫结构的Python程序:
```python
import turtle
from random import randint, choice
def draw_maze(width=20, height=20):
screen = turtle.Screen()
maze_drawer = turtle.Turtle(shape='turtle')
cell_size = 20
walls = [[True]*width for _ in range(height)]
def is_wall(x, y): return not (walls[y][x])
directions = [(0,-1), (-1,0), (+1,0), (0,+1)]
stack = []
visited = set()
start_x, start_y = randint(0,width-1),randint(0,height-1)
current_cell = (start_x,start_y)
while True:
neighbors = ((current_cell[0]+dx,current_cell[1]+dy)
for dx, dy in directions)
unvisited_neighbors = [
n for n in neighbors if all([
0<=n[0]<width,
0<=n[1]<height,
n not in visited])]
if unvisited_neighbors:
next_cell = choice(unvisited_neighbors)
# Remove wall between cells.
walls[(next_cell[1]+current_cell[1])//2][(next_cell[0]+current_cell[0])//2]=False
stack.append(current_cell)
visited.add(next_cell)
current_cell = next_cell
elif stack:
current_cell = stack.pop()
else:
break
def draw_square(x,y,size,color="black"):
"""Helper function to draw a square at position."""
maze_drawer.penup()
maze_drawer.goto(-cell_size*width/2+x*cell_size-cell_size/2, -cell_size*height/2+y*cell_size-cell_size/2)
maze_drawer.pendown()
maze_drawer.color(color)
for i in range(4):
maze_drawer.forward(size)
maze_drawer.left(90)
for row_index,row in enumerate(walls):
for col_index,is_a_wall in enumerate(row):
if is_a_wall:
draw_square(col_index,row_index,cell_size,"blue")
screen.mainloop()
draw_maze()
```
这段代码定义了一个名为 `draw_maze()` 的函数,它接受两个参数——宽度和高度,默认情况下都设置为20。此函数内部实现了深度优先搜索算法以构建迷宫,并通过移除墙壁的方式形成通道。最后利用`turtle`中的绘图功能把整个迷宫呈现出来。
阅读全文
相关推荐

















