import pygame
import random

# --- 配置参数 ---
WIDTH, HEIGHT = 800, 600
TILE = 40  # 每个格子的像素大小
FPS = 60

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
PLAYER_COLOR = (0, 200, 255)

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, self.y * TILE
        if self.visited:
            pygame.draw.rect(sc, BLACK, (x, y, TILE, TILE))
        
        # 绘制墙壁
        if self.walls['top']:
            pygame.draw.line(sc, WHITE, (x, y), (x + TILE, y), 2)
        if self.walls['right']:
            pygame.draw.line(sc, WHITE, (x + TILE, y), (x + TILE, y + TILE), 2)
        if self.walls['bottom']:
            pygame.draw.line(sc, WHITE, (x + TILE, y + TILE), (x, y + TILE), 2)
        if self.walls['left']:
            pygame.draw.line(sc, WHITE, (x, y + TILE), (x, y), 2)

    def check_neighbors(self, cols, rows, grid):
        neighbors = []
        def get_cell(x, y):
            if x < 0 or x > cols - 1 or y < 0 or y > rows - 1:
                return None
            return grid[x + y * cols]

        top = get_cell(self.x, self.y - 1)
        right = get_cell(self.x + 1, self.y)
        bottom = get_cell(self.x, self.y + 1)
        left = get_cell(self.x - 1, self.y)

        if top and not top.visited: neighbors.append(top)
        if right and not right.visited: neighbors.append(right)
        if bottom and not bottom.visited: neighbors.append(bottom)
        if left and not left.visited: neighbors.append(left)

        return random.choice(neighbors) if neighbors else None

def remove_walls(current, next):
    dx = current.x - next.x
    if dx == 1:
        current.walls['left'] = False
        next.walls['right'] = False
    elif dx == -1:
        current.walls['right'] = False
        next.walls['left'] = False
    dy = current.y - next.y
    if dy == 1:
        current.walls['top'] = False
        next.walls['bottom'] = False
    elif dy == -1:
        current.walls['bottom'] = False
        next.walls['top'] = False

def generate_maze(cols, rows):
    grid = [Cell(col, row) for row in range(rows) for col in range(cols)]
    current_cell = grid[0]
    stack = []
    count = 1

    while count < len(grid):
        current_cell.visited = True
        next_cell = current_cell.check_neighbors(cols, rows, grid)
        if next_cell:
            next_cell.visited = True
            stack.append(current_cell)
            remove_walls(current_cell, next_cell)
            current_cell = next_cell
            count += 1
        elif stack:
            current_cell = stack.pop()
    return grid

def main():
    pygame.init()
    sc = pygame.display.set_mode((WIDTH, HEIGHT))
    pygame.display.set_caption("随机迷宫大冒险")
    clock = pygame.time.Clock()

    cols, rows = WIDTH // TILE, HEIGHT // TILE
    grid = generate_maze(cols, rows)
    
    # 玩家属性
    player_x, player_y = 0, 0
    goal_x, goal_y = cols - 1, rows - 1

    running = True
    while running:
        sc.fill(pygame.Color('darkslategray'))

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            
            # 移动逻辑与碰撞检测
            if event.type == pygame.KEYDOWN:
                current_cell = grid[player_x + player_y * cols]
                if event.key == pygame.K_UP and not current_cell.walls['top']:
                    player_y -= 1
                elif event.key == pygame.K_DOWN and not current_cell.walls['bottom']:
                    player_y += 1
                elif event.key == pygame.K_LEFT and not current_cell.walls['left']:
                    player_x -= 1
                elif event.key == pygame.K_RIGHT and not current_cell.walls['right']:
                    player_x += 1

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

        # 绘制终点
        pygame.draw.rect(sc, GREEN, (goal_x * TILE + 5, goal_y * TILE + 5, TILE - 10, TILE - 10))

        # 绘制玩家
        pygame.draw.circle(sc, PLAYER_COLOR, (player_x * TILE + TILE//2, player_y * TILE + TILE//2), TILE//3)

        # 胜利检测
        if player_x == goal_x and player_y == goal_y:
            print("你赢了！生成新关卡...")
            grid = generate_maze(cols, rows)
            player_x, player_y = 0, 0

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

    pygame.quit()

if __name__ == "__main__":
    main()