import pygame
import random

# --- 配置参数 ---
WIDTH, HEIGHT = 800, 600
TILE_SIZE = 40  # 每个格子的大小
COLS, ROWS = WIDTH // TILE_SIZE, HEIGHT // TILE_SIZE

# 颜色定义
COLOR_BG = (20, 20, 20)
COLOR_WALL = (100, 100, 100)
COLOR_PLAYER = (50, 255, 50)
COLOR_GOAL = (255, 50, 50)
COLOR_PATH = (40, 40, 40)

class Cell:
    def __init__(self, x, y):
        self.x, self.y = x, y
        self.walls = {'top': True, 'right': True, 'bottom': True, 'left': True}
        self.visited = False

    def draw(self, sc):
        x, y = self.x * TILE_SIZE, self.y * TILE_SIZE
        if self.visited:
            pygame.draw.rect(sc, COLOR_PATH, (x, y, TILE_SIZE, TILE_SIZE))
        
        # 绘制墙线
        line_width = 2
        if self.walls['top']:
            pygame.draw.line(sc, COLOR_WALL, (x, y), (x + TILE_SIZE, y), line_width)
        if self.walls['right']:
            pygame.draw.line(sc, COLOR_WALL, (x + TILE_SIZE, y), (x + TILE_SIZE, y + TILE_SIZE), line_width)
        if self.walls['bottom']:
            pygame.draw.line(sc, COLOR_WALL, (x + TILE_SIZE, y + TILE_SIZE), (x, y + TILE_SIZE), line_width)
        if self.walls['left']:
            pygame.draw.line(sc, COLOR_WALL, (x, y + TILE_SIZE), (x, y), line_width)

    def check_neighbors(self, grid):
        neighbors = []
        # 定义上下左右四个方向
        directions = [('top', 0, -1), ('right', 1, 0), ('bottom', 0, 1), ('left', -1, 0)]
        for wall, dx, dy in directions:
            nx, ny = self.x + dx, self.y + dy
            if 0 <= nx < COLS and 0 <= ny < ROWS:
                neighbor = grid[ny * COLS + nx]
                if not neighbor.visited:
                    neighbors.append((wall, neighbor))
        return random.choice(neighbors) if neighbors else None

def remove_walls(current, next_cell, wall_type):
    # 移除当前格子的墙和目标格子的对应墙
    current.walls[wall_type] = False
    opposite = {'top': 'bottom', 'right': 'left', 'bottom': 'top', 'left': 'right'}
    next_cell.walls[opposite[wall_type]] = False

def generate_maze():
    grid = [Cell(col, row) for row in range(ROWS) for col in range(COLS)]
    current = grid[0]
    stack = []
    visited_count = 1

    while visited_count < len(grid):
        current.visited = True
        next_data = current.check_neighbors(grid)
        if next_data:
            wall_type, next_cell = next_data
            next_cell.visited = True
            visited_count += 1
            stack.append(current)
            remove_walls(current, next_cell, wall_type)
            current = next_cell
        elif stack:
            current = stack.pop()
    return grid

def main():
    pygame.init()
    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    pygame.display.set_caption("DFS 随机迷宫生成器")
    clock = pygame.time.Clock()

    # 生成迷宫
    grid = generate_maze()
    
    # 玩家属性
    p_x, p_y = 0, 0
    goal_x, goal_y = COLS - 1, ROWS - 1

    running = True
    while running:
        screen.fill(COLOR_BG)
        
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            
            # 移动逻辑
            if event.type == pygame.KEYDOWN:
                current_cell = grid[p_y * COLS + p_x]
                if event.key == pygame.K_UP and not current_cell.walls['top']:
                    p_y -= 1
                if event.key == pygame.K_DOWN and not current_cell.walls['bottom']:
                    p_y += 1
                if event.key == pygame.K_LEFT and not current_cell.walls['left']:
                    p_x -= 1
                if event.key == pygame.K_RIGHT and not current_cell.walls['right']:
                    p_x += 1

        # 绘制迷宫
        for cell in grid:
            cell.draw(screen)

        # 绘制终点
        pygame.draw.rect(screen, COLOR_GOAL, 
                         (goal_x * TILE_SIZE + 5, goal_y * TILE_SIZE + 5, TILE_SIZE - 10, TILE_SIZE - 10))

        # 绘制玩家
        pygame.draw.circle(screen, COLOR_PLAYER, 
                           (p_x * TILE_SIZE + TILE_SIZE // 2, p_y * TILE_SIZE + TILE_SIZE // 2), TILE_SIZE // 3)

        # 胜利检测
        if p_x == goal_x and p_y == goal_y:
            print("恭喜你赢了！重新生成迷宫...")
            grid = generate_maze()
            p_x, p_y = 0, 0

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

    pygame.quit()

if __name__ == "__main__":
    main()