python随机迷宫生成
时间: 2023-10-13 20:27:59 浏览: 82
以下是使用Python生成随机迷宫的示例代码:
```python
import random
N = 10 # 迷宫大小
WALL = "#"
PATH = " "
START = "S"
END = "E"
# 初始化迷宫
maze = [[WALL] * N for i in range(N)]
# 随机生成起始点和终点
start = (random.randint(0, N-1), random.randint(0, N-1))
end = (random.randint(0, N-1), random.randint(0, N-1))
# 确保起始点和终点不在同一位置
while start == end:
end = (random.randint(0, N-1), random.randint(0, N-1))
# 标记起始点和终点
maze[start[0]][start[1]] = START
maze[end[0]][end[1]] = END
# 随机生成路径
visited = set()
stack = [start]
while stack:
curr = stack.pop()
visited.add(curr)
neighbors = [(curr[0]-1, curr[1]), (curr[0]+1, curr[1]), (curr[0], curr[1]-1), (curr[0], curr[1]+1)]
random.shuffle(neighbors)
for neighbor in neighbors:
if neighbor[0] < 0 or neighbor[0] >= N or neighbor[1] < 0 or neighbor[1] >= N:
continue
if neighbor in visited:
continue
stack.append(neighbor)
maze[neighbor[0]][neighbor[1]] = PATH
# 输出迷宫
for i in range(N):
for j in range(N):
print(maze[i][j], end="")
print()
```
该代码使用随机化深度优先搜索算法生成路径,并使用二维列表表示迷宫。WALL代表墙壁,PATH代表通路,START和END分别代表起点和终点。运行代码可以得到类似以下的输出:
```
##########
# S #
# # # # #
# # #
# #### # #
# # # #
# # # # #
# # # ##
# # # E#
##########
```
阅读全文