import tkinter as tk
import random
import time

root = tk.Tk()
root.title("鼠标点击反应训练")
WIDTH = 800
HEIGHT = 600
root.geometry(f"{WIDTH}x{HEIGHT}")

canvas = tk.Canvas(root, bg="white")
canvas.pack(fill=tk.BOTH, expand=True)

# 游戏参数
circle_radius = 25
target_count = 10
score = 0
current_target = 0
start_time = 0
target_appear_time = 0
game_state = "ready"  # ready / playing / end
circle_x = 0
circle_y = 0
reaction_times = []
circle_id = None
text_id = None

def spawn_circle():
    """生成随机圆点坐标，不超出画布"""
    x = random.randint(circle_radius, WIDTH - circle_radius)
    y = random.randint(circle_radius, HEIGHT - circle_radius)
    return x, y

def draw_text(msg, x, y, color="black", size=14):
    return canvas.create_text(x, y, text=msg, fill=color, font=("SimHei", size))

def clear_all():
    canvas.delete("all")

def on_click(event):
    global game_state, score, current_target, start_time, target_appear_time, circle_x, circle_y, circle_id
    mx, my = event.x, event.y
    if game_state == "ready":
        # 开局重置
        game_state = "playing"
        score = 0
        current_target = 0
        reaction_times.clear()
        start_time = time.time()
        circle_x, circle_y = spawn_circle()
        target_appear_time = time.time()
        clear_all()
        circle_id = canvas.create_oval(
            circle_x - circle_radius, circle_y - circle_radius,
            circle_x + circle_radius, circle_y + circle_radius,
            fill="#dc2222"
        )
    elif game_state == "playing":
        # 判断点击是否命中圆点
        dx = mx - circle_x
        dy = my - circle_y
        dist = (dx**2 + dy**2)**0.5
        if dist <= circle_radius:
            rt = time.time() - target_appear_time
            reaction_times.append(rt)
            score += 1
            current_target += 1
            if current_target >= target_count:
                game_state = "end"
            else:
                circle_x, circle_y = spawn_circle()
                target_appear_time = time.time()
                canvas.delete(circle_id)
                circle_id = canvas.create_oval(
                    circle_x - circle_radius, circle_y - circle_radius,
                    circle_x + circle_radius, circle_y + circle_radius,
                    fill="#dc2222"
                )
    elif game_state == "end":
        game_state = "ready"
        draw_ready_screen()

def draw_ready_screen():
    clear_all()
    draw_text("鼠标反应训练", 400, 120, color="#dc2222", size=24)
    draw_text(f"目标数量：{target_count} 个圆点", 400, 180, size=16)
    draw_text("点击圆点得分，测试你的反应速度", 400, 220, size=14)
    draw_text("点击屏幕任意位置开始游戏", 400, 280, color="#28a828", size=16)

def update_game():
    if game_state == "playing":
        clear_all()
        # 重绘圆点
        canvas.create_oval(
            circle_x - circle_radius, circle_y - circle_radius,
            circle_x + circle_radius, circle_y + circle_radius,
            fill="#dc2222"
        )
        elapsed = time.time() - start_time
        draw_text(f"得分: {score}/{target_count}", 80, 25, size=14)
        draw_text(f"总用时: {elapsed:.2f}s", 80, 55, size=14)
    elif game_state == "end":
        clear_all()
        total_time = time.time() - start_time
        avg_rt = sum(reaction_times) / len(reaction_times) if reaction_times else 0
        draw_text("训练完成！", 400, 100, color="#28a828", size=24)
        draw_text(f"总耗时：{total_time:.2f} 秒", 400, 160, size=16)
        draw_text(f"平均反应：{avg_rt:.3f} 秒", 400, 200, size=16)
        draw_text("各次反应时间：", 400, 240, size=14)
        for i, t in enumerate(reaction_times):
            draw_text(f"{i+1}: {t:.3f}s", 400, 270 + i*24, size=12)
        draw_text("点击屏幕重新开始", 400, 520, color="#dc2222", size=16)
    root.after(30, update_game)

canvas.bind("<Button-1>", on_click)
draw_ready_screen()
update_game()
root.mainloop()
