
import pygame
import random
import time

# 初始化pygame
pygame.init()

# 窗口尺寸
WIDTH, HEIGHT = 1000, 700
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("反应速度点击训练")
clock = pygame.time.Clock()

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (20, 20, 20)
RED = (255, 60, 60)
GREEN = (50, 230, 80)
BLUE = (30, 150, 255)
YELLOW = (255, 220, 0)
PURPLE = (190, 70, 230)
COLOR_LIST = [RED, GREEN, BLUE, YELLOW, PURPLE]

# 通用字体（兼容Windows/Mac/Linux，不会缺失）
try:
    font_big = pygame.font.SysFont("Microsoft YaHei", 48)
    font_mid = pygame.font.SysFont("Microsoft YaHei", 34)
    font_small = pygame.font.SysFont("Microsoft YaHei", 24)
except:
    # 找不到微软雅黑自动切换默认字体
    font_big = pygame.font.Font(None, 48)
    font_mid = pygame.font.Font(None, 34)
    font_small = pygame.font.Font(None, 24)

# 重置游戏函数
def reset_game():
    global score, click_num, total_react, start_time, target, gap, last_spawn, game_on
    score = 0
    click_num = 0
    total_react = 0.0
    start_time = time.time()
    gap = 1300    # 圆点刷新间隔 毫秒
    last_spawn = pygame.time.get_ticks()
    target = None
    game_on = True

reset_game()

# 主循环
run = True
while run:
    now_tick = pygame.time.get_ticks()
    now_sec = time.time()
    screen.fill(BLACK)

    # 事件监听
    for event in pygame.event.get():
        # 关闭窗口
        if event.type == pygame.QUIT:
            run = False
        # 鼠标点击
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            mx, my = pygame.mouse.get_pos()
            if target:
                tx, ty, r = target["x"], target["y"], target["r"]
                # 计算距离判断是否点中圆点
                distance = ((mx - tx)**2 + (my - ty)**2)**0.5
                if distance <= r:
                    # 计算单次反应时间
                    react_ms = (now_sec - target["spawn_time"]) * 1000
                    total_react += react_ms
                    click_num += 1
                    score += 1
                    # 加快刷新速度，最低400ms
                    gap = max(400, gap - 25)
                    target = None
        # R键重新开局
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_r:
                reset_game()

    # 生成新圆点
    if game_on and target is None and now_tick - last_spawn > gap:
        radius = random.randint(25, 50)
        x = random.randint(radius, WIDTH - radius)
        y = random.randint(90, HEIGHT - radius)
        color = random.choice(COLOR_LIST)
        target = {
            "x": x,
            "y": y,
            "r": radius,
            "color": color,
            "spawn_time": now_sec
        }
        last_spawn = now_tick

    # 绘制圆点
    if target:
        pygame.draw.circle(screen, target["color"], (target["x"], target["y"]), target["r"])
        pygame.draw.circle(screen, WHITE, (target["x"], target["y"]), target["r"] // 3)

    # 计算游戏数据
    game_time = round(now_sec - start_time, 2)
    if click_num > 0:
        average_react = round(total_react / click_num, 1)
    else:
        average_react = 0

    # 绘制顶部文字面板
    text_score = font_mid.render(f"得分：{score}", True, WHITE)
    text_alltime = font_mid.render(f"总时长：{game_time}s", True, WHITE)
    text_avg = font_mid.render(f"平均反应：{average_react}ms", True, GREEN)
    text_hint = font_small.render("R键重新开始 | 限时60秒", True, (160,160,160))

    screen.blit(text_score, (15, 12))
    screen.blit(text_alltime, (210, 12))
    screen.blit(text_avg, (470, 12))
    screen.blit(text_hint, (15, 50))

    # 60秒限时结束
    if game_time >= 60:
        end_text = font_big.render("时间结束！按R再来一次", True, RED)
        text_rect = end_text.get_rect(center=(WIDTH//2, HEIGHT//2))
        screen.blit(end_text, text_rect)
        game_on = False

    pygame.display.update()
    clock.tick(60)

pygame.quit()