使用Python实现一个简单的迷宫游戏
以下是一个使用Python实现的简单迷宫游戏的示例代码:
import random
# 定义迷宫的大小
MAZE_SIZE = 10
# 创建迷宫地图
def create_maze():
maze = [['.' for _ in range(MAZE_SIZE)] for _ in range(MAZE_SIZE)]
# 随机选择起始点和终点
start = (random.randint(0, MAZE_SIZE-1), 0)
end = (random.randint(0, MAZE_SIZE-1), MAZE_SIZE-1)
maze[start[0]][start[1]] = 'S'
maze[end[0]][end[1]] = 'E'
return maze, start, end
# 打印迷宫地图
def print_maze(maze):
for row in maze:
print(' '.join(row))
# 移动玩家
def move(maze, player, move):
x, y = player
dx, dy = move
# 如果移动超出边界或者是墙壁,则不移动
if x+dx<0 or x+dx>=MAZE_SIZE or y+dy<0 or y+dy>=MAZE_SIZE or maze[x+dx][y+dy] == '#':
return player
# 移动玩家
return x+dx, y+dy
# 主程序
def main():
maze, start, end = create_maze()
player = start
while True:
print_maze(maze)
# 玩家输入移动方向
direction = input("Please enter the move direction (w/a/s/d): ")
if direction == 'w':
player = move(maze, player, (-1, 0))
elif direction == 'a':
player = move(maze, player, (0, -1))
elif direction == 's':
player = move(maze, player, (1, 0))
elif direction == 'd':
player = move(maze, player, (0, 1))
else:
print("Invalid direction!")
continue
# 如果玩家到达终点则游戏结束
if player == end:
print("Congratulations! You win!")
break
if __name__ == "__main__":
main()
这个迷宫游戏程序使用二维数组表示迷宫,其中.表示空地,#表示墙壁,S表示起点,E表示终点。玩家可以通过输入w(上)、a(左)、s(下)、d(右)来移动。玩家在移动过程中不能超出迷宫边界或穿过墙壁。
在游戏开始时,程序会随机选择起点和终点,并打印迷宫地图。玩家通过输入移动方向来移动,输入无效的方向会提示玩家重新输入。如果玩家成功到达终点,则游戏结束并显示“Congratulations! You win!”的消息。
以下是一个使用示例:
`
. . . . . . . . S .
. . . . # . # . . .
# # . . # . # . # .
# # . . . . # . # #
# . # . # . . # . #
# . # . . . . # . #
# . # . # . # . # #
# . . . # . . . . #
# # # # # # # # # #
# . . . # . . . . E
Please enter the move direction (w/a/s/d): d
. . . . . . . . S .
. . . . # . # . . .
# # . . # . # . # .
# # . . . . # . # #
# . # . # . . # . #
# . # . . . . . # #
# . # . # . # . # #
# . . . # . . . . #
# # # # # # # # # #
# . . . # . . . E
Please enter the move direction (w/a/s/d): s
. . . . . . . . S .
. . . . # . # . . .
# # . . # . # . # .
# # . . . . # . # #
# . # . # . . # . #
# . # . . . . . # #
# . # . # . # . # #
# . . . # . . . . #
# # # # # # # # # #
# . .
