写出简单的走迷宫游戏代码
时间: 2023-06-08 13:07:37 浏览: 67
好的,以下是一个简单的走迷宫游戏的代码示例,使用Python编写:
```
# 创建迷宫地图
maze = [
[1, 1, 1, 1, 1],
[1, 0, 0, 0, 1],
[1, 0, 1, 0, 1],
[1, 0, 0, 0, 1],
[1, 1, 1, 1, 1]
]
# 定义起点和终点位置
start_row = 1
start_col = 1
end_row = 3
end_col = 3
# 定义可走方向
directions = {'N': (-1, 0), 'E': (0, 1), 'S': (1, 0), 'W': (0, -1)}
# 定义搜索路径的栈
stack = [(start_row, start_col)]
# 开始搜索
while stack:
row, col = stack[-1]
if row == end_row and col == end_col:
print("已找到终点!")
break
for direction in directions:
dr, dc = directions[direction]
if maze[row+dr][col+dc] == 0:
stack.append((row+dr, col+dc))
maze[row+dr][col+dc] = 2
break
else:
stack.pop()
# 输出结果
print("搜索路径:")
for row in maze:
print(row)
```
以上代码会搜索从起点到终点的路径,并输出结果。在这个代码中,使用了一个栈来保存当前的路径,如果从当前位置没有可走的方向,就将这个位置从栈中弹出。如果在搜索过程中找到了终点,就会停止搜索,并输出结果。