import pygame
import random
import sys

# 窗口设置
WIDTH = 600
HEIGHT = 600
CELL_SIZE = 30
COLS = WIDTH // CELL_SIZE
ROWS = HEIGHT // CELL_SIZE

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

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

# 迷宫生成 深度优先DFS算法
class MazeGenerator:
    def __init__(self, cols, rows):
        self.cols = cols
        self.rows = rows
        self.grid = [[1 for _ in range(cols)] for _ in range(rows)]
        self.visited = [[False for _ in range(cols)] for _ in range(rows)]
        self.dirs = [(-2, 0), (2, 0), (0, -2), (0, 2)]

    def generate(self):
        stack = []
        start_x, start_y = 1, 1
        self.grid[start_y][start_x] = 0
        self.visited[start_y][start_x] = True
        stack.append((start_x, start_y))

        while stack:
            x, y = stack[-1]
            neighbors = []
            for dx, dy in self.dirs:
                nx = x + dx
                ny = y + dy
                if 0 < nx < self.cols - 1 and 0 < ny < self.rows - 1:
                    if not self.visited[ny][nx]:
                        neighbors.append((nx, ny, dx//2, dy//2))
            if neighbors:
                nx, ny, wdx, wdy = random.choice(neighbors)
                self.visited[ny][nx] = True
                self.grid[y + wdy][x + wdx] = 0
                self.grid[ny][nx] = 0
                stack.append((nx, ny))
            else:
                stack.pop()
        return self.grid

# 游戏主逻辑
def main():
    maze = MazeGenerator(COLS, ROWS)
    map_data = maze.generate()

    # 玩家起点、终点
    player_x, player_y = 1, 1
    end_x, end_y = COLS - 2, ROWS - 2

    running = True
    while running:
        screen.fill(BLACK)

        # 绘制迷宫
        for y in range(ROWS):
            for x in range(COLS):
                rect = pygame.Rect(x*CELL_SIZE, y*CELL_SIZE, CELL_SIZE-1, CELL_SIZE-1)
                if map_data[y][x] == 0:
                    pygame.draw.rect(screen, WHITE, rect)
                else:
                    pygame.draw.rect(screen, BLACK, rect)

        # 绘制终点
        end_rect = pygame.Rect(end_x*CELL_SIZE, end_y*CELL_SIZE, CELL_SIZE-1, CELL_SIZE-1)
        pygame.draw.rect(screen, RED, end_rect)

        # 绘制玩家
        player_rect = pygame.Rect(player_x*CELL_SIZE, player_y*CELL_SIZE, CELL_SIZE-1, CELL_SIZE-1)
        pygame.draw.rect(screen, BLUE, player_rect)

        # 事件监听
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        # 按键持续移动
        keys = pygame.key.get_pressed()
        nx, ny = player_x, player_y
        if keys[pygame.K_UP]:
            ny -= 1
        if keys[pygame.K_DOWN]:
            ny += 1
        if keys[pygame.K_LEFT]:
            nx -= 1
        if keys[pygame.K_RIGHT]:
            nx += 1

        # 碰撞检测，不能穿墙
        if 0 <= nx < COLS and 0 <= ny < ROWS:
            if map_data[ny][nx] == 0:
                player_x, player_y = nx, ny

        # 判断到达终点
        if player_x == end_x and player_y == end_y:
            font = pygame.font.SysFont(None, 60)
            text = font.render("恭喜通关！", True, GREEN)
            screen.blit(text, (WIDTH//2 - 120, HEIGHT//2))
            pygame.display.flip()
            pygame.time.wait(2000)
            # 重新生成新迷宫
            map_data = maze.generate()
            player_x, player_y = 1, 1

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

    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()