import pygame
import random

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

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BLUE = (0, 100, 255)   # 玩家
RED = (255, 50, 50)    # 终点
GREEN = (50, 255, 50)  # 路径（可选）

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, screen):
        x, y = self.x * TILE_SIZE, self.y * TILE_SIZE
        if self.walls['top']:
            pygame.draw.line(screen, WHITE, (x, y), (x + TILE_SIZE, y), 2)
        if self.walls['right']:
            pygame.draw.line(screen, WHITE, (x + TILE_SIZE, y), (x + TILE_SIZE, y + TILE_SIZE), 2)
        if self.walls['bottom']:
            pygame.draw.line(screen, WHITE, (x + TILE_SIZE, y + TILE_SIZE), (x, y + TILE_SIZE), 2)
        if self.walls['left']:
            pygame.draw.line(screen, WHITE, (x, y + TILE_SIZE), (x, y), 2)

def get_neighbors(cell, grid):
    neighbors = []
    x, y = cell.x, cell.y
    directions = [('top', (x, y-1)), ('right', (x+1, y)), ('bottom', (x, y+1)), ('left', (x-1, y))]
    
    for wall, (nx, ny) in directions:
        if 0 <= nx < COLS and 0 <= ny < ROWS:
            neighbors.append((wall, grid[ny * COLS + nx]))
    return neighbors

def remove_walls(current, next_cell, wall_type):
    if wall_type == 'top':
        current.walls['top'] = False
        next_cell.walls['bottom'] = False
    elif wall_type == 'right':
        current.walls['right'] = False
        next_cell.walls['left'] = False
    elif wall_type == 'bottom':
        current.walls['bottom'] = False
        next_cell.walls['top'] = False
    elif wall_type == 'left':
        current.walls['left'] = False
        next_cell.walls['right'] = False

def generate_maze():
    grid = [Cell(x, y) for y in range(ROWS) for x in range(COLS)]
    stack = []
    current = grid[0]
    current.visited = True
    
    while True:
        # 寻找未访问的邻居
        unvisited_neighbors = [n for n in get_neighbors(current, grid) if not n[1].visited]
        
        if unvisited_neighbors:
            wall, next_cell = random.choice(unvisited_neighbors)
            next_cell.visited = True
            stack.append(current)
            remove_walls(current, next_cell, wall)
            current = next_cell
        elif stack:
            current = stack.pop()
        else:
            break
    return grid

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

    # 生成迷宫
    grid = generate_maze()
    
    # 玩家属性
    player_pos = [0, 0] # 格子坐标
    goal_pos = [COLS - 1, ROWS - 1]

    running = True
    while running:
        screen.fill(BLACK)
        
        # 1. 事件处理
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.KEYDOWN:
                x, y = player_pos
                current_cell = grid[y * COLS + x]
                if event.key == pygame.K_UP and not current_cell.walls['top']:
                    player_pos[1] -= 1
                if event.key == pygame.K_DOWN and not current_cell.walls['bottom']:
                    player_pos[1] += 1
                if event.key == pygame.K_LEFT and not current_cell.walls['left']:
                    player_pos[0] -= 1
                if event.key == pygame.K_RIGHT and not current_cell.walls['right']:
                    player_pos[0] += 1

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

        # 3. 绘制终点
        goal_rect = (goal_pos[0]*TILE_SIZE + 5, goal_pos[1]*TILE_SIZE + 5, TILE_SIZE - 10, TILE_SIZE - 10)
        pygame.draw.rect(screen, RED, goal_rect)

        # 4. 绘制玩家
        player_rect = (player_pos[0]*TILE_SIZE + 10, player_pos[1]*TILE_SIZE + 10, TILE_SIZE - 20, TILE_SIZE - 20)
        pygame.draw.rect(screen, BLUE, player_rect)

        # 5. 胜利检测
        if player_pos == goal_pos:
            print("你赢了！")
            grid = generate_maze() # 重新生成
            player_pos = [0, 0]

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

    pygame.quit()

if __name__ == "__main__":
    main()