python迷宫源程序清单
时间: 2023-06-22 15:31:56 浏览: 106
以下是一个简单的 Python 迷宫游戏源代码清单:
```python
import random
# 迷宫的大小
SIZE = 10
# 定义迷宫的墙壁和通路
WALL = "#"
PATH = " "
# 初始化迷宫
maze = [[WALL for x in range(SIZE)] for y in range(SIZE)]
# 随机选择起点和终点
start = (random.randint(0, SIZE - 1), 0)
end = (random.randint(0, SIZE - 1), SIZE - 1)
# 定义迷宫生成算法
def generate_maze(start):
stack = [start]
while stack:
x, y = stack.pop()
maze[x][y] = PATH
directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]
random.shuffle(directions)
for dx, dy in directions:
new_x, new_y = x + dx, y + dy
if 0 <= new_x < SIZE and 0 <= new_y < SIZE and maze[new_x][new_y] == WALL:
stack.append((new_x, new_y))
# 生成迷宫
generate_maze(start)
# 输出迷宫
for row in maze:
print("".join(row))
```
这段代码使用了深度优先搜索算法生成迷宫,并使用二维列表表示迷宫。你可以根据自己的需求修改代码来生成不同形状的迷宫。
阅读全文