import pygame
import random
import sys

# ---------- 配置 ----------
CELL = 32               # 格子大小
COLS = 21              # 列数（奇数）
ROWS = 21              # 行数（奇数）
WIDTH = COLS * CELL
HEIGHT = ROWS * CELL
FPS = 60

# 颜色
WHITE = (245, 245, 245)
BLACK = (20, 20, 20)
GREEN = (0, 200, 100)
RED = (220, 50, 50)
BLUE = (50, 100, 220)

# ---------- 迷宫生成（DFS） ----------
def generate_maze(w, h):
    maze = [[1] * w for _ in range(h)]

    def carve(x, y):
        maze[y][x] = 0
        dirs = [(2, 0), (-2, 0), (0, 2), (0, -2)]
        random.shuffle(dirs)
        for dx, dy in dirs:
            nx, ny = x + dx, y + dy
            if 0 <= nx < w and 0 <= ny < h and maze[ny][nx] == 1:
                maze[y + dy // 2][x + dx // 2] = 0
                carve(nx, ny)

    carve(1, 1)
    return maze


# ---------- 玩家 ----------
class Player:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.rect = pygame.Rect(
            x * CELL + 6, y * CELL + 6, CELL - 12, CELL - 12
        )

    def move(self, dx, dy, maze):
        nx = self.x + dx
        ny = self.y + dy
        if maze[ny][nx] == 0:
            self.x, self.y = nx, ny
            self.rect.x = nx * CELL + 6
            self.rect.y = ny * CELL + 6


# ---------- 主游戏 ----------
def main():
    pygame.init()
    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    pygame.display.set_caption("Pygame 迷宫")
    clock = pygame.time.Clock()

    maze = generate_maze(COLS, ROWS)
    player = Player(1, 1)
    exit_pos = (COLS - 2, ROWS - 2)

    running = True
    while running:
        clock.tick(FPS)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    player.move(0, -1, maze)
                elif event.key == pygame.K_DOWN:
                    player.move(0, 1, maze)
                elif event.key == pygame.K_LEFT:
                    player.move(-1, 0, maze)
                elif event.key == pygame.K_RIGHT:
                    player.move(1, 0, maze)

        # 胜利判断
        if (player.x, player.y) == exit_pos:
            print("🎉 你走出迷宫了！")
            running = False

        # ---------- 绘制 ----------
        screen.fill(BLACK)

        for y in range(ROWS):
            for x in range(COLS):
                if maze[y][x] == 1:
                    pygame.draw.rect(
                        screen, WHITE,
                        (x * CELL, y * CELL, CELL, CELL)
                    )

        pygame.draw.rect(
            screen, GREEN,
            (exit_pos[0] * CELL, exit_pos[1] * CELL, CELL, CELL)
        )

        pygame.draw.rect(screen, BLUE, player.rect)
        pygame.display.flip()

    pygame.quit()
    sys.exit()


if __name__ == "__main__":
    main()