```python
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def create_maze(width, height, depth):
maze = np.ones((width, height, depth), dtype=int)
def carve_path(x, y, z):
maze[x, y, z] = 0
directions = [(1,0,0), (-1,0,0), (0,1,0), (0,-1,0), (0,0,1), (0,0,-1)]
np.random.shuffle(directions)
for dx, dy, dz in directions:
nx, ny, nz = x + dx*2, y + dy*2, z + dz*2
if 0 <= nx < width and 0 <= ny < height and 0 <= nz < depth and maze[nx, ny, nz] == 1:
maze[y+dy][x+dx] = 0
carve_path(nx, ny, nz)
carve_path(width//2, height//2, depth//2)
return maze
def plot_maze(maze):
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.imshow(maze, cmap='binary')
plt.show()
生成并显示迷宫
width, height, depth = 10, 10, 10
maze = create_maze(width, height, depth)
plot_maze(maze)
```
这个代码示例使用NumPy创建一个三维数组来表示迷宫,其中1表示墙壁,0表示通路。通过递归函数`carve_path`,从中心开始随机选择方向挖洞,直到所有单元格都被访问过。最后,使用Matplotlib的3D模块将迷宫可视化。
你可以根据需要调整迷宫的宽度、高度和深度,以及修改`carve_path`函数中的逻辑来生成不同结构和风格的迷宫。