import pygame
import random
import sys
import time

# 初始化
pygame.init()

# 游戏配置
CELL = 30
COLS = 25
ROWS = 18
WIDTH = COLS * CELL
HEIGHT = ROWS * CELL
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("迷宫游戏")

# 颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (30, 144, 255)
RED = (255, 60, 60)
GREEN = (50, 205, 50)
YELLOW = (255, 215, 0)
GRAY = (50, 50, 50)

# 强制使用支持中文的字体（永不失效）
def font(size):
    return pygame.font.SysFont(["simhei", "microsoft yahei", "arial unicode ms"], size)

# 玩家
class Player:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def draw(self):
        pygame.draw.circle(screen, BLUE, (self.x + CELL//2, self.y + CELL//2), CELL//2 - 4)

# 敌人
class Enemy:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.speed = 1.8

    def move_towards(self, px, py, walls):
        dx = 0
        dy = 0
        if self.x < px: dx = self.speed
        if self.x > px: dx = -self.speed
        if self.y < py: dy = self.speed
        if self.y > py: dy = -self.speed

        new_x = self.x + dx
        new_y = self.y + dy
        if not check_collide(new_x, self.y, walls):
            self.x = new_x
        if not check_collide(self.x, new_y, walls):
            self.y = new_y

    def draw(self):
        pygame.draw.circle(screen, RED, (self.x + CELL//2, self.y + CELL//2), CELL//2 - 4)

# 碰撞检测
def check_collide(x, y, walls):
    r = pygame.Rect(x, y, CELL-1, CELL-1)
    for w in walls:
        if r.colliderect(w):
            return True
    return False

# 生成随机迷宫
def generate_maze():
    grid = [[1 for _ in range(COLS)] for _ in range(ROWS)]
    stack = []
    cx, cy = 1, 1
    grid[cy][cx] = 0
    stack.append((cx, cy))

    dirs = [(-2,0),(2,0),(0,-2),(0,2)]
    while stack:
        cx, cy = stack[-1]
        neighbors = []
        for dx, dy in dirs:
            nx = cx + dx
            ny = cy + dy
            if 1 <= nx < COLS-1 and 1 <= ny < ROWS-1 and grid[ny][nx] == 1:
                neighbors.append((nx, ny))
        if neighbors:
            nx, ny = random.choice(neighbors)
            grid[ny][nx] = 0
            grid[cy + (ny - cy)//2][cx + (nx - cx)//2] = 0
            stack.append((nx, ny))
        else:
            stack.pop()

    walls = []
    for y in range(ROWS):
        for x in range(COLS):
            if grid[y][x] == 1:
                walls.append(pygame.Rect(x*CELL, y*CELL, CELL, CELL))
    return walls

# 找空白点
def find_empty(grid):
    while True:
        x = random.randint(1, COLS-2)
        y = random.randint(1, ROWS-2)
        if grid[y][x] == 0:
            return x*CELL, y*CELL

# 主游戏
def game():
    walls = generate_maze()
    grid = [[1 if any(w.x == x*CELL and w.y == y*CELL for w in walls) else 0 for x in range(COLS)] for y in range(ROWS)]
    px, py = find_empty(grid)
    ex, ey = find_empty(grid)
    end_x, end_y = find_empty(grid)

    player = Player(px, py)
    enemy = Enemy(ex, ey)
    clock = pygame.time.Clock()
    start_time = time.time()
    win = False

    running = True
    while running:
        screen.fill(BLACK)
        clock.tick(60)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

        # 移动
        move_speed = 3
        nx, ny = player.x, player.y
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT] or keys[pygame.K_a]: nx -= move_speed
        if keys[pygame.K_RIGHT] or keys[pygame.K_d]: nx += move_speed
        if keys[pygame.K_UP] or keys[pygame.K_w]: ny -= move_speed
        if keys[pygame.K_DOWN] or keys[pygame.K_s]: ny += move_speed

        if not check_collide(nx, player.y, walls):
            player.x = nx
        if not check_collide(player.x, ny, walls):
            player.y = ny

        enemy.move_towards(player.x, player.y, walls)

        # 判定
        end_rect = pygame.Rect(end_x, end_y, CELL, CELL)
        player_rect = pygame.Rect(player.x, player.y, CELL, CELL)
        enemy_rect = pygame.Rect(enemy.x, enemy.y, CELL, CELL)
        
        if player_rect.colliderect(end_rect):
            win = True
            running = False
        if player_rect.colliderect(enemy_rect):
            running = False

        # 绘制
        for w in walls:
            pygame.draw.rect(screen, GRAY, w)
        pygame.draw.rect(screen, GREEN, end_rect)
        player.draw()
        enemy.draw()

        # 时间
        timer = int(time.time() - start_time)
        time_text = font(32).render(f"时间：{timer} 秒", True, YELLOW)
        screen.blit(time_text, (10, 10))

        pygame.display.flip()

    return win, timer

# 结束界面
def show_end(win, time_use):
    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:
                game()

        if win:
            t1 = font(50).render("恭喜通关！", True, GREEN)
            t2 = font(32).render(f"用时：{time_use} 秒", True, WHITE)
        else:
            t1 = font(50).render("你被抓住了！", True, RED)
            t2 = font(32).render("按任意键重新开始", True, WHITE)

        screen.blit(t1, (WIDTH//2 - t1.get_width()//2, HEIGHT//2 - 50))
        screen.blit(t2, (WIDTH//2 - t2.get_width()//2, HEIGHT//2 + 20))
        pygame.display.flip()

# 启动
if __name__ == "__main__":
    result, time_val = game()
    show_end(result, time_val)