python 走迷宫小游戏
时间: 2023-12-26 14:28:04 浏览: 35
以下是一个简单的Python代码示例,用于实现走迷宫小游戏:
```python
# 定义迷宫地图
maze = [
[1, 1, 1, 1, 1],
[1, 0, 0, 0, 1],
[1, 1, 1, 0, 1],
[1, 0, 0, 0, 1],
[1, 1, 1, 1, 1]
]
# 定义起点和终点
start = (1, 1)
end = (3, 3)
# 定义可行动的四个方向
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
# 定义一个空的路径列表
path = []
# 定义一个函数,用于找到从起点到终点的路径
def find_path(maze, start, end, path):
# 判断当前位置是否为终点
if start == end:
return True
# 判断当前位置是否为墙壁或已经走过
if maze[start[0]][start[1]] == 1 or start in path:
return False
# 将当前位置加入路径列表
path.append(start)
# 遍历四个方向
for direction in directions:
next_pos = (start[0] + direction[0], start[1] + direction[1])
# 递归调用自身,寻找下一个位置
if find_path(maze, next_pos, end, path):
return True
# 如果四个方向都无法找到路径,则将当前位置从路径列表中移除
path.remove(start)
return False
# 调用函数,找到路径
if find_path(maze, start, end, path):
print("找到路径:", path)
else:
print("无法找到路径")
```
这段代码使用递归的方式,从起点开始,尝试向四个方向移动,直到找到终点或无法继续移动为止。如果找到路径,则输出路径列表;如果无法找到路径,则输出"无法找到路径"。