import pygame
import random
import sys
import os

# ========== 配置参数 ==========
WIDTH = 800
HEIGHT = 640
CELL_SIZE = 32
COLS = WIDTH // CELL_SIZE
ROWS = HEIGHT // CELL_SIZE

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (30, 30, 30)
RED = (220, 50, 50)
GREEN = (50, 220, 80)
BLUE = (70, 130, 230)

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

# 安全创建字体（修复字体崩溃问题）
try:
    # 优先尝试黑体
    font = pygame.font.SysFont("simhei", 36)
except:
    try:
        font = pygame.font.SysFont("Microsoft YaHei", 36)
    except:
        # 兜底默认字体，一定不会报错（英文提示）
        font = pygame.font.Font(None, 36)


# 迷宫单元格类
class Cell:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.walls = {"top": True, "right": True, "bottom": True, "left": True}
        self.visited = False

    def draw(self):
        x1 = self.x * CELL_SIZE
        y1 = self.y * CELL_SIZE
        if self.walls["top"]:
            pygame.draw.line(screen, WHITE, (x1, y1), (x1 + CELL_SIZE, y1), 2)
        if self.walls["right"]:
            pygame.draw.line(screen, WHITE, (x1 + CELL_SIZE, y1), (x1 + CELL_SIZE, y1 + CELL_SIZE), 2)
        if self.walls["bottom"]:
            pygame.draw.line(screen, WHITE, (x1, y1 + CELL_SIZE), (x1 + CELL_SIZE, y1 + CELL_SIZE), 2)
        if self.walls["left"]:
            pygame.draw.line(screen, WHITE, (x1, y1), (x1, y1 + CELL_SIZE), 2)

# 移除相邻格子之间的墙
def remove_wall(a, b):
    dx = a.x - b.x
    dy = a.y - b.y
    if dx == 1:
        a.walls["left"] = False
        b.walls["right"] = False
    elif dx == -1:
        a.walls["right"] = False
        b.walls["left"] = False
    if dy == 1:
        a.walls["top"] = False
        b.walls["bottom"] = False
    elif dy == -1:
        a.walls["bottom"] = False
        b.walls["top"] = False

# 获取未访问邻居
def get_neighbors(cell, grid):
    neighbors = []
    x, y = cell.x, cell.y
    dirs = [
        (x, y-1), # top
        (x+1, y), # right
        (x, y+1), # bottom
        (x-1, y)  # left
    ]
    for nx, ny in dirs:
        if 0 <= nx < COLS and 0 <= ny < ROWS:
            neighbor = grid[ny][nx]
            if not neighbor.visited:
                neighbors.append(neighbor)
    return neighbors

# 生成迷宫（深度优先DFS）
def generate_maze():
    grid = [[Cell(x, y) for x in range(COLS)] for y in range(ROWS)]
    stack = []
    current = grid[0][0]
    current.visited = True
    while True:
        neighbors = get_neighbors(current, grid)
        if neighbors:
            next_cell = random.choice(neighbors)
            next_cell.visited = True
            stack.append(current)
            remove_wall(current, next_cell)
            current = next_cell
        elif stack:
            current = stack.pop()
        else:
            break
    return grid

# 检测碰撞：玩家能否移动到目标格子
def can_move(grid, cell_x, cell_y, direction):
    if not (0 <= cell_x < COLS and 0 <= cell_y < ROWS):
        return False
    cell = grid[cell_y][cell_x]
    if direction == "up" and cell.walls["top"]:
        return False
    if direction == "down" and cell.walls["bottom"]:
        return False
    if direction == "left" and cell.walls["left"]:
        return False
    if direction == "right" and cell.walls["right"]:
        return False
    return True

def main():
    grid = generate_maze()
    # 玩家起始位置
    player_x = 0
    player_y = 0
    end_x = COLS - 1
    end_y = ROWS - 1
    game_win = False

    while True:
        screen.fill(BLACK)
        # 事件监听
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if game_win:
                    # 按任意键重新生成迷宫
                    grid = generate_maze()
                    player_x, player_y = 0, 0
                    game_win = False
                    continue
                # 移动控制
                if event.key == pygame.K_UP:
                    if can_move(grid, player_x, player_y, "up"):
                        player_y -= 1
                elif event.key == pygame.K_DOWN:
                    if can_move(grid, player_x, player_y, "down"):
                        player_y += 1
                elif event.key == pygame.K_LEFT:
                    if can_move(grid, player_x, player_y, "left"):
                        player_x -= 1
                elif event.key == pygame.K_RIGHT:
                    if can_move(grid, player_x, player_y, "right"):
                        player_x += 1

        # 绘制迷宫墙壁
        for row in grid:
            for cell in row:
                cell.draw()

        # 绘制起点(绿色)终点(红色)
        pygame.draw.circle(screen, GREEN,
                           (player_x*CELL_SIZE+CELL_SIZE//2, player_y*CELL_SIZE+CELL_SIZE//2), CELL_SIZE//3)
        pygame.draw.circle(screen, RED,
                           (end_x*CELL_SIZE+CELL_SIZE//2, end_y*CELL_SIZE+CELL_SIZE//2), CELL_SIZE//3)

        # 判断胜利
        if player_x == end_x and player_y == end_y and not game_win:
            game_win = True

        if game_win:
            # 如果没有中文字体，中文会变成方框，我提供英文备选
            text_surface = font.render("You Win! Press any key to restart", True, BLUE)
            screen.blit(text_surface, (WIDTH//2 - text_surface.get_width()//2, HEIGHT//2))

        pygame.display.flip()
        clock.tick(60)

if __name__ == "__main__":
    main()