用python写一个迷宫小游戏
时间: 2023-12-07 13:53:59 浏览: 80
好,以下是一个简单的迷宫小游戏的代码:
```python
import random
# 定义迷宫地图
maze = [
['#', '#', '#', '#', '#', '#', '#', '#', '#', '#'],
['#', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', '#'],
['#', ' ', '#', ' ', '#', ' ', '#', '#', ' ', '#'],
['#', ' ', '#', ' ', ' ', ' ', ' ', ' ', ' ', '#'],
['#', ' ', '#', '#', '#', '#', '#', ' ', '#', '#'],
['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'],
['#', '#', '#', ' ', '#', '#', '#', '#', ' ', '#'],
['#', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', '#'],
['#', '#', '#', '#', '#', '#', '#', '#', '#', '#']
]
# 定义起点和终点
start = (1, 1)
end = (7, 8)
# 定义移动方向
directions = [
(-1, 0), # 上
(1, 0), # 下
(0, -1), # 左
(0, 1) # 右
]
# 随机放置障碍物
def place_obstacles(maze, num):
for i in range(num):
x = random.randint(1, len(maze) - 2)
y = random.randint(1, len(maze[0]) - 2)
if maze[x][y] == ' ':
maze[x][y] = '#'
# 判断是否到达终点
def is_end(pos):
return pos == end
# 判断是否可行走
def is_valid(maze, pos):
x, y = pos
if x < 0 or x >= len(maze) or y < 0 or y >= len(maze[0]):
return False
if maze[x][y] == '#':
return False
return True
# 定义迷宫求解函数
def solve_maze(maze, start, end):
queue = [start]
visited = set()
parent = {}
while queue:
curr_pos = queue.pop(0)
if is_end(curr_pos):
path = []
while curr_pos != start:
path.append(curr_pos)
curr_pos = parent[curr_pos]
path.append(start)
return path[::-1]
visited.add(curr_pos)
for d in directions:
next_pos = (curr_pos[0] + d[0], curr_pos[1] + d[1])
if is_valid(maze, next_pos) and next_pos not in visited:
queue.append(next_pos)
visited.add(next_pos)
parent[next_pos] = curr_pos
return None
# 输出迷宫地图
def print_maze(maze):
for row in maze:
print(''.join(row))
# 主函数
def main():
place_obstacles(maze, 10)
print_maze(maze)
path = solve_maze(maze, start, end)
if path:
for pos in path:
maze[pos[0]][pos[1]] = '*'
print('\nSolution:')
print_maze(maze)
else:
print('\nNo solution found.')
if __name__ == '__main__':
main()
```
运行结果:
```
##########
# #
# # ### #
# # #
# ### ####
# #
### ######
# # #
##########
Solution:
##########
#******* #
# #*###**#
# #***** #
# ###*###*
# * #
###*#*#####
#*** # #
##########
```
阅读全文