随机生成迷宫地图代码python
时间: 2023-11-21 22:57:58 浏览: 224
以下是使用Python生成随机迷宫地图的代码,主要使用了递归回溯算法:
```python
import random
def generate_maze(width, height):
# 初始化地图
maze = [[0 for y in range(height)] for x in range(width)]
# 随机选择起点
x, y = random.randint(0, width-1), random.randint(0, height-1)
maze[x][y] = 1
# 递归回溯算法生成迷宫
generate_maze_helper(x, y, maze)
return maze
def generate_maze_helper(x, y, maze):
# 随机打乱四个方向的顺序
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
random.shuffle(directions)
for dx, dy in directions:
# 计算下一个点的坐标
nx, ny = x + dx, y + dy
# 判断下一个点是否在地图内
if nx < 0 or nx >= len(maze) or ny < 0 or ny >= len(maze[0]):
continue
# 判断下一个点是否已经被访问过
if maze[nx][ny] != 0:
continue
# 打通当前点和下一个点之间的墙
if dx == 1:
maze[x][y] |= 2
maze[nx][ny] |= 8
elif dx == -1:
maze[x][y] |= 8
maze[nx][ny] |= 2
elif dy == 1:
maze[x][y] |= 4
maze[nx][ny] |= 1
elif dy == -1:
maze[x][y] |= 1
maze[nx][ny] |= 4
# 递归访问下一个点
generate_maze_helper(nx, ny, maze)
# 生成一个10x10的迷宫
maze = generate_maze(10, 10)
# 打印迷宫
for y in range(len(maze[0])):
for x in range(len(maze)):
print("#" if maze[x][y] & 1 else " ", end="")
print("#" if maze[x][y] & 2 else " ", end="")
print("#" if maze[x][y] & 4 else " ", end="")
print("#" if maze[x][y] & 8 else " ", end="")
print()
```
阅读全文