#迷宫游戏
迷宫规则如下:
p为您现在所在的位置,E为本迷宫游戏的出口!!!
您可以通过键入 w(上),a(左),s(下),d(右)
改变您所在的位置,移动位置至E点即可通关迷宫!!!
# 规则介绍
def rule():
print('-' * 31)
print(' ' * 10 + "欢迎来到迷宫!")
print('-' * 31)
print("""\
迷宫规则如下:
p为您现在所在的位置,E为本迷宫游戏的出口!!!
您可以通过键入 w(上),a(左),s(下),d(右)
改变您所在的位置,移动位置至E点即可通关迷宫!!!""")
print('-' * 31)
# 定义迷宫地图
maze = [
['#', '#', '#', '#', '#', '#'],
['#', ' ', ' ', ' ', ' ', '#'],
['#', '#', '#', '#', ' ', '#'],
['#', ' ', ' ', ' ', ' ', '#'],
['#', ' ', ' ', ' ', 'E', '#'],
['#', '#', '#', '#', '#', '#']
]
# 定义玩家的初始位置
player_pos = (1, 1)
# 定义移动方向及其对应的坐标变化
directions = {
'w': (-1, 0), # 上
's': (1, 0), # 下
'a': (0, -1), # 左
'd': (0, 1) # 右
}
# 检查玩家位置是否有效
def is_valid_position(x, y):
return 0 < x < len(maze) and 0 < y < len(maze[0]) and (x, y) not in[(2,i) for i in range(1,4)]
# 打印迷宫及玩家位置
def print_maze(pos):
for i, row in enumerate(maze):
for j, cell in enumerate(row):
if (i, j) == pos:
print('P', end='')
else:
print(cell, end='')
print()
# 游戏主循环
def game_loop():
rule()
while True:
# 打印当前迷宫和玩家位置
global player_pos
print_maze(player_pos)
# 获取玩家输入
move = input("请输入移动方向(w/a/s/d):").strip().lower()
# 检查输入是否有效
if move not in directions:
print("无效的方向,请重新输入。")
continue
# 计算新的位置
new_x, new_y = player_pos[0] + directions[move][0], player_pos[1] + directions[move][1]
# 检查新位置是否有效
if is_valid_position(new_x, new_y):
player_pos = (new_x, new_y)
else:
print("撞到墙了,无法移动。")
continue
# 检查是否到达出口
if maze[player_pos[0]][player_pos[1]] == 'E':
print("恭喜你,找到出口了!")
return
# 开始游戏
if __name__ == '__main__':
game_loop()