基于Python的简单迷宫游戏。游戏使用控制台界面,玩家可以通过键盘输入来移动。迷宫使用二维列表来表示,玩家可以在迷宫中上下左右移动,目标是从起点到达终点。游戏开始后,玩家可以使用 w、a、s、d 键来上下左右移动,目标是从起点 S 到达终点 E。每次移动后迷宫会重新打印,玩家可以看到自己的当前位置。
import random
def create_maze(width, height):
"""创建一个随机迷宫,S代表起点,E代表终点,空格代表路径,#代表墙"""
maze = [['#' for _ in range(width)] for _ in range(height)]
# 随机生成起点和终点
start_x, start_y = random.randint(1, width-2), random.randint(1, height-2)
end_x, end_y = random.randint(1, width-2), random.randint(1, height-2)
maze[start_y][start_x] = 'S'
maze[end_y][end_x] = 'E'
# 随机生成路径
for _ in range((width * height) // 3):
x, y = random.randint(1, width-2), random.randint(1, height-2)
maze[y][x] = ' '
maze[start_y][start_x] = 'S'
maze[end_y][end_x] = 'E'
return maze, (start_x, start_y), (end_x, end_y)
def print_maze(maze):
"""打印迷宫"""
for row in maze:
print(''.join(row))
def move_player(maze, position, move):
"""根据玩家的输入移动玩家的位置"""
x, y = position
if move == 'w' and maze[y-1][x] != '#':
y -= 1
elif move == 's' and maze[y+1][x] != '#':
y += 1
elif move == 'a' and maze[y][x-1] != '#':
x -= 1
elif move == 'd' and maze[y][x+1] != '#':
x += 1
return x, y
def play_maze_game():
width, height = 10, 10
maze, start, end = create_maze(width, height)
position = start
print("欢迎来到迷宫游戏!使用 'w', 'a', 's', 'd' 移动,目标是到达 'E'。")
print_maze(maze)
while position != end:
move = input("你的移动 (w/a/s/d): ").lower()
if move in ['w', 'a', 's', 'd']:
new_position = move_player(maze, position, move)
if new_position != position:
maze[position[1]][position[0]] = ' '
position = new_position
if position == end:
print("恭喜你到达了终点!")
break
maze[position[1]][position[0]] = 'S'
print_maze(maze)
else:
print("不能移动到该位置,请重试。")
else:
print("无效的输入,请使用 'w', 'a', 's', 'd' 进行移动。")
if __name__ == "__main__":
play_maze_game()
运行效果截图: