用python写一个三维迷宫程序
时间: 2023-12-16 20:03:57 浏览: 77
Python 实现递归法解决迷宫问题的示例代码
好的,以下是一个简单的三维迷宫程序的示例代码:
```python
import random
# 定义迷宫大小
maze_size = (5, 5, 5)
# 定义迷宫墙壁和通道的标记
WALL = "#"
PASSAGE = " "
# 初始化迷宫
maze = [[[WALL for z in range(maze_size[2])] for y in range(maze_size[1])] for x in range(maze_size[0])]
# 随机生成迷宫
def generate_maze(x, y, z):
maze[x][y][z] = PASSAGE
directions = [(1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1)]
random.shuffle(directions)
for dx, dy, dz in directions:
nx, ny, nz = x + dx, y + dy, z + dz
if nx < 0 or nx >= maze_size[0] or ny < 0 or ny >= maze_size[1] or nz < 0 or nz >= maze_size[2]:
continue
if maze[nx][ny][nz] == WALL:
maze[x + dx // 2][y + dy // 2][z + dz // 2] = PASSAGE
generate_maze(nx, ny, nz)
# 随机选择起点和终点
start = (random.randint(0, maze_size[0] - 1), random.randint(0, maze_size[1] - 1), random.randint(0, maze_size[2] - 1))
end = (random.randint(0, maze_size[0] - 1), random.randint(0, maze_size[1] - 1), random.randint(0, maze_size[2] - 1))
while start == end:
end = (random.randint(0, maze_size[0] - 1), random.randint(0, maze_size[1] - 1), random.randint(0, maze_size[2] - 1))
# 生成迷宫
generate_maze(0, 0, 0)
# 输出迷宫
for z in range(maze_size[2]):
print("Layer", z + 1)
for y in range(maze_size[1]):
for x in range(maze_size[0]):
if (x, y, z) == start:
print("S", end="")
elif (x, y, z) == end:
print("E", end="")
else:
print(maze[x][y][z], end="")
print()
print()
```
这个程序使用递归深度优先搜索算法生成了一个三维迷宫,并随机选择了起点和终点。你可以根据需要修改迷宫大小和起点终点的位置。
阅读全文