Python实现随机迷宫游戏详解

游戏

运行代码后,会显示一个随机生成的迷宫和一个红色圆形玩家。
使用方向键控制玩家移动,避开墙壁,找到绿色方块表示的出口。
到达出口后,游戏会自动生成新的迷宫并重置玩家位置,进入下一局。

界面

代码

import pygame
import sys
import random

# 初始化Pygame
pygame.init()

# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

# 设置屏幕大小
WIDTH, HEIGHT = 400, 400
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("随机迷宫游戏")

# 定义方块大小
MAZE_SIZE = 8  # 迷宫大小 (8x8)
BLOCK_SIZE = WIDTH // MAZE_SIZE

# 定义玩家初始位置
player_pos = [1, 1]


# 生成随机迷宫
def generate_maze(size):
    # 初始化迷宫,全部为墙壁
    maze = [[1 for _ in range(size)] for _ in range(size)]

    # 使用深度优先搜索算法生成迷宫
    def dfs(x, y):
        maze[y][x] = 0  # 打通当前单元格
        directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
        random.shuffle(directions)  # 随机打乱方向
        for dx, dy in directions:
            nx, ny = x + dx * 2, y + dy * 2
            if 0 <= nx < size and 0 <= ny < size and maze[ny][nx] == 1:
                maze[y + dy][x + dx] = 0  # 打通路径
                dfs(nx, ny)

    dfs(1, 1)  # 从起点开始生成迷宫
    maze[1][1] = 0  # 确保起点是空的
    maze[size - 2][size - 2] = 2  # 设置出口
    return maze


# 重置游戏状态
def reset_game():
    global maze, player_pos
    maze = generate_maze(MAZE_SIZE)
    player_pos = [1, 1]


# 游戏主循环
def main():
    clock = pygame.time.Clock()
    running = True
    reset_game()  # 初始化迷宫和玩家位置

    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.KEYDOWN:
                # 处理玩家移动
                if event.key == pygame.K_UP:
                    move_player(0, -1)
                elif event.key == pygame.K_DOWN:
                    move_player(0, 1)
                elif event.key == pygame.K_LEFT:
                    move_player(-1, 0)
                elif event.key == pygame.K_RIGHT:
                    move_player(1, 0)

        # 绘制迷宫和玩家
        screen.fill(WHITE)
        draw_maze()
        draw_player()
        pygame.display.flip()

        # 检查是否到达出口
        if maze[player_pos[1]][player_pos[0]] == 2:
            print("恭喜你,成功找到出口!进入下一局...")
            reset_game()  # 重置游戏状态

        clock.tick(30)

    pygame.quit()
    sys.exit()


# 绘制迷宫
def draw_maze():
    for y, row in enumerate(maze):
        for x, block in enumerate(row):
            if block == 1:
                pygame.draw.rect(screen, BLACK, (x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE))
            elif block == 2:
                pygame.draw.rect(screen, GREEN, (x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE))


# 绘制玩家
def draw_player():
    pygame.draw.circle(screen, RED,
                       (player_pos[0] * BLOCK_SIZE + BLOCK_SIZE // 2, player_pos[1] * BLOCK_SIZE + BLOCK_SIZE // 2),
                       BLOCK_SIZE // 3)


# 移动玩家
def move_player(dx, dy):
    new_x = player_pos[0] + dx
    new_y = player_pos[1] + dy
    # 检查新位置是否合法
    if 0 <= new_x < len(maze[0]) and 0 <= new_y < len(maze):
        if maze[new_y][new_x] != 1:  # 不能穿过墙壁
            player_pos[0] = new_x
            player_pos[1] = new_y


if __name__ == "__main__":
    main()

作者:C7211BA

物联沃分享整理
物联沃-IOTWORD物联网 » Python实现随机迷宫游戏详解

发表回复