欢迎访问宙启技术站
智能推送

用Python编写的简易迷宫游戏

发布时间:2023-12-04 18:55:37

以下是使用Python编写的简易迷宫游戏的代码。游戏有一个5x5的迷宫,玩家需要控制一个小人从迷宫的起始位置到达终点位置。迷宫由墙壁(#)和通道(.)组成,小人用P表示,起始位置用S表示,终点位置用E表示。玩家可以通过上、下、左、右四个方向的操作来控制小人移动。游戏规则是小人只能通过通道(.)移动,不能穿过墙壁(#)。以下是代码和一个使用例子:

maze = [
    ['#', '#', '#', '#', '#'],
    ['#', '.', '.', '.', '#'],
    ['#', '#', '#', '.', '#'],
    ['#', '.', '#', '.', '#'],
    ['#', '#', '#', '#', '#']
]

def print_maze(maze):
    for row in maze:
        print(" ".join(row))

def find_start(maze):
    for i in range(len(maze)):
        for j in range(len(maze[0])):
            if maze[i][j] == 'S':
                return i, j

def move(maze, direction):
    x, y = find_start(maze)
    if direction == 'up':
        if x > 0 and maze[x-1][y] != '#':
            maze[x][y] = '.'
            maze[x-1][y] = 'P'
    elif direction == 'down':
        if x < len(maze)-1 and maze[x+1][y] != '#':
            maze[x][y] = '.'
            maze[x+1][y] = 'P'
    elif direction == 'left':
        if y > 0 and maze[x][y-1] != '#':
            maze[x][y] = '.'
            maze[x][y-1] = 'P'
    elif direction == 'right':
        if y < len(maze[0])-1 and maze[x][y+1] != '#':
            maze[x][y] = '.'
            maze[x][y+1] = 'P'

def game_over(maze):
    for row in maze:
        if 'P' in row:
            return False
    return True

def play_game():
    print("Welcome to the Maze Game!")
    print("You need to navigate the character 'P' from 'S' to 'E'.")
    print("Use 'W' to move up, 'S' to move down, 'A' to move left, 'D' to move right.")
    print("Press 'Q' to quit the game.")
    print_maze(maze)

    while not game_over(maze):
        direction = input("Enter your move: ")
        if direction == 'W':
            move(maze, 'up')
        elif direction == 'S':
            move(maze, 'down')
        elif direction == 'A':
            move(maze, 'left')
        elif direction == 'D':
            move(maze, 'right')
        elif direction == 'Q':
            print("Game Over")
            break
        print_maze(maze)

        if game_over(maze):
            print("Congratulations! You reached the end of the maze!")

play_game()

使用例子:

Welcome to the Maze Game!
You need to navigate the character 'P' from 'S' to 'E'.
Use 'W' to move up, 'S' to move down, 'A' to move left, 'D' to move right.
Press 'Q' to quit the game.
# # # # #
# . . . #
# # # . #
# . # . #
# # # # #
Enter your move: D
# # # # #
# . . . #
# # # . #
# . # P #
# # # # #
Enter your move: D
# # # # #
# . . . #
# # # . #
# . . P #
# # # # #
Enter your move: D
# # # # #
# . . . #
# # # . #
# . . . P
# # # # #
Enter your move: D
# # # # #
# . . . #
# # # . #
# . . . .
# # # # #
Congratulations! You reached the end of the maze!