prim算法随机生成迷宫动图
时间: 2023-06-25 15:06:06 浏览: 154
好的,我可以为你提供一份Python代码实现Prim算法生成迷宫,并用动画展示的方法。你需要安装Python的相关库`numpy`, `matplotlib`, `pillow`和`imageio`。以下是代码:
```python
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import imageio
def create_maze(width, height):
maze = np.zeros((height, width))
start_x = np.random.randint(0, width)
start_y = np.random.randint(0, height)
maze[start_y, start_x] = 1
walls = []
if start_x > 0:
walls.append((start_x - 1, start_y, start_x, start_y))
if start_x < width - 1:
walls.append((start_x, start_y, start_x + 1, start_y))
if start_y > 0:
walls.append((start_x, start_y - 1, start_x, start_y))
if start_y < height - 1:
walls.append((start_x, start_y, start_x, start_y + 1))
while walls:
wall = walls.pop(np.random.randint(0, len(walls)))
x1, y1, x2, y2 = wall
if maze[y1, x1] == 1 and maze[y2, x2] == 0:
maze[y2, x2] = 1
if x2 > 0:
walls.append((x2 - 1, y2, x2, y2))
if x2 < width - 1:
walls.append((x2, y2, x2 + 1, y2))
if y2 > 0:
walls.append((x2, y2 - 1, x2, y2))
if y2 < height - 1:
walls.append((x2, y2, x2, y2 + 1))
elif maze[y2, x2] == 1 and maze[y1, x1] == 0:
maze[y1, x1] = 1
if x1 > 0:
walls.append((x1 - 1, y1, x1, y1))
if x1 < width - 1:
walls.append((x1, y1, x1 + 1, y1))
if y1 > 0:
walls.append((x1, y1 - 1, x1, y1))
if y1 < height - 1:
walls.append((x1, y1, x1, y1 + 1))
return maze
def animate_maze(maze, filename):
height, width = maze.shape
frames = []
for i in range(height):
for j in range(width):
if maze[i, j] == 0:
img = np.ones((10, 10, 3))
img[:, :, 0] = 0
else:
img = np.zeros((10, 10, 3))
img[:, :, 0] = 1
frames.append(img)
imageio.mimsave(filename, frames, fps=30)
maze = create_maze(50, 50)
animate_maze(maze, 'maze.gif')
maze_img = np.zeros((maze.shape[0] * 10, maze.shape[1] * 10))
for i in range(maze.shape[0]):
for j in range(maze.shape[1]):
if maze[i, j] == 0:
maze_img[i*10:(i+1)*10, j*10:(j+1)*10] = 255
maze_img = Image.fromarray(maze_img.astype(np.uint8))
maze_img.show()
```
这份代码将会生成一个大小为50x50的迷宫,并将迷宫动画保存为一个GIF文件,同时还会将迷宫以图像的形式展示出来。你可以尝试修改大小、保存格式等参数,自己生成不同的结果。
阅读全文