python生成随机可行迷宫
时间: 2023-11-29 15:47:22 浏览: 136
python 随机迷宫
以下是使用Python生成随机可行迷宫的代码示例:
```python
import random
def generate_maze(width, height):
# 初始化迷宫
maze = [[0 for x in range(width)] for y in range(height)]
# 随机选择起点
x, y = random.randint(0, width-1), random.randint(0, height-1)
maze[y][x] = 1
# 生成迷宫
generate_maze_helper(x, y, maze)
return maze
def generate_maze_helper(x, y, maze):
# 定义四个方向
directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]
# 随机打乱方向
random.shuffle(directions)
for dx, dy in directions:
# 计算下一个点的坐标
nx, ny = x + dx, y + dy
# 判断下一个点是否在迷宫内
if nx < 0 or ny < 0 or nx >= len(maze[0]) or ny >= len(maze):
continue
# 判断下一个点是否已经访问过
if maze[ny][nx] != 0:
continue
# 将当前点和下一个点之间的墙打通
maze[y + dy // 2][x + dx // 2] = 1
# 递归生成迷宫
generate_maze_helper(nx, ny, maze)
# 生成一个10x10的迷宫
maze = generate_maze(10, 10)
# 打印迷宫
for row in maze:
print(' '.join(['*' if cell == 0 else ' ' for cell in row]))
```
阅读全文