import pygame
import random
import sys

# ------------------- 配置 -------------------
CELL = 40
VISION = 9
SCALE = 4

WIDTH = VISION * CELL * SCALE
HEIGHT = VISION * CELL * SCALE

FPS = 60
WALL = (60, 60, 60)
PATH = (220, 220, 220)
PLAYER = (50, 150, 255)
EXIT = (255, 100, 100)
FOG = (10, 10, 10)
WIN_COLOR = (0, 200, 0)

pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("迷宫")
clock = pygame.time.Clock()


# ------------------- 迷宫生成（DFS） -------------------
def generate_maze(cols, rows):
    maze = [[1 for _ in range(cols)] for _ in range(rows)]
    stack = [(1, 1)]
    maze[1][1] = 0
    directions = [(0, -2), (0, 2), (-2, 0), (2, 0)]

    while stack:
        cx, cy = stack[-1]
        random.shuffle(directions)
        carved = False
        for dx, dy in directions:
            nx, ny = cx + dx, cy + dy
            if 0 < nx < cols and 0 < ny < rows and maze[ny][nx] == 1:
                maze[cy + dy // 2][cx + dx // 2] = 0
                maze[ny][nx] = 0
                stack.append((nx, ny))
                carved = True
                break
        if not carved:
            stack.pop()

    return maze


# ------------------- 关卡配置 -------------------
LEVELS = [
    {"cols": 21, "rows": 15, "wall": (60, 60, 60)},
    {"cols": 25, "rows": 17, "wall": (90, 60, 40)},
    {"cols": 29, "rows": 19, "wall": (40, 90, 70)},
    {"cols": 33, "rows": 21, "wall": (80, 50, 100)},
]


def build_level(index):
    cfg = LEVELS[index % len(LEVELS)]
    cols, rows = cfg["cols"], cfg["rows"]
    maze = generate_maze(cols, rows)

    # 确保三个角落都是通路（DFS 可能没挖到角落，手动打通）
    corners = [
        (cols - 2, rows - 2),   # 右下
        (cols - 2, 1),          # 右上
        (1, rows - 2),          # 左下
    ]

    for cx, cy in corners:
        maze[cy][cx] = 0
        # 把角落和主路连起来（打通相邻的一格墙）
        if cx == 1:
            maze[cy][cx + 1] = 0  # 左下连右边
        elif cy == 1:
            maze[cy + 1][cx] = 0  # 右上连下边
        else:
            maze[cy - 1][cx] = 0  # 右下连上边

    # 随机选一个角落作为终点
    exit_pos = random.choice(corners)

    return {
        "maze": maze,
        "cols": cols,
        "rows": rows,
        "wall": cfg["wall"],
        "px": 1,
        "py": 1,
        "exit": exit_pos,
        "won": False,
    }


# ------------------- 绘制 -------------------
def draw(state):
    maze = state["maze"]
    cols, rows = state["cols"], state["rows"]
    px, py = state["px"], state["py"]
    ex, ey = state["exit"]

    half = VISION // 2
    left = px - half
    top = py - half
    view_size = VISION * CELL
    view = pygame.Surface((view_size, view_size))
    view.fill(FOG)

    for y in range(VISION):
        for x in range(VISION):
            wx = left + x
            wy = top + y
            if 0 <= wx < cols and 0 <= wy < rows:
                color = PATH if maze[wy][wx] == 0 else state["wall"]
                pygame.draw.rect(
                    view, color,
                    pygame.Rect(x * CELL, y * CELL, CELL, CELL)
                )

    # 终点（红块 + 白色边框）
    if 0 <= ex - left < VISION and 0 <= ey - top < VISION:
        r = pygame.Rect((ex - left) * CELL, (ey - top) * CELL, CELL, CELL)
        pygame.draw.rect(view, EXIT, r)
        pygame.draw.rect(view, (255, 255, 255), r, width=3)

    # 玩家（视野中心）
    cx = half * CELL + 4
    cy = half * CELL + 4
    pygame.draw.rect(
        view, PLAYER,
        pygame.Rect(cx, cy, CELL - 8, CELL - 8),
        border_radius=8
    )

    screen.blit(pygame.transform.scale(view, (WIDTH, HEIGHT)), (0, 0))

    if state["won"]:
        pygame.draw.rect(
            screen, WIN_COLOR,
            pygame.Rect(WIDTH // 2 - 90, HEIGHT // 2 - 30, 180, 60)
        )
        for i in range(5):
            pygame.draw.rect(
                screen, (255, 255, 255),
                pygame.Rect(WIDTH // 2 - 70 + i * 30, HEIGHT // 2 - 8, 22, 16)
            )


# ------------------- 主循环 -------------------
def main():
    level_index = 0
    state = build_level(level_index)

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

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

            elif event.type == pygame.KEYDOWN:
                if state["won"]:
                    level_index += 1
                    state = build_level(level_index)
                    continue

                nx, ny = state["px"], state["py"]
                if event.key == pygame.K_LEFT:
                    nx -= 1
                elif event.key == pygame.K_RIGHT:
                    nx += 1
                elif event.key == pygame.K_UP:
                    ny -= 1
                elif event.key == pygame.K_DOWN:
                    ny += 1

                if (0 <= nx < state["cols"] and
                    0 <= ny < state["rows"] and
                    state["maze"][ny][nx] == 0):
                    state["px"], state["py"] = nx, ny

                if (state["px"], state["py"]) == state["exit"]:
                    state["won"] = True

        draw(state)
        pygame.display.flip()

    pygame.quit()
    sys.exit()


if __name__ == "__main__":
    main()