基于Python的迷宫游戏

基于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()

运行效果截图:
在这里插入图片描述

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

PeterClerk

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值