import tkinter as tk
import random

root = tk.Tk()
root.title("配色小练习")
root.geometry("600x420")
root.resizable(False, False)

# 全局变量
score = 0
level = 4  # 默认候选色块数量
target_color = ""
btn_list = []

# 随机生成十六进制颜色 #RRGGBB
def random_hex_color():
    r = random.randint(0, 255)
    g = random.randint(0, 255)
    b = random.randint(0, 255)
    return f"#{r:02X}{g:02X}{b:02X}"

# 刷新一轮题目
def new_round():
    global target_color, btn_list
    # 清空旧按钮
    for btn in btn_list:
        btn.destroy()
    btn_list.clear()

    # 生成目标色
    target_color = random_hex_color()
    target_canvas.config(bg=target_color)

    # 生成答案+干扰色
    color_options = [target_color]
    while len(color_options) < level:
        c = random_hex_color()
        if c not in color_options:
            color_options.append(c)
    random.shuffle(color_options)

    # 生成选择按钮
    for idx, col in enumerate(color_options):
        btn = tk.Button(
            btn_frame,
            width=6,
            height=3,
            bg=col,
            command=lambda c=col: check_choose(c)
        )
        btn.grid(row=idx//4, column=idx%4, padx=6, pady=6)
        btn_list.append(btn)

    tip_text.set("请选出上方相同颜色")

# 点击选择颜色判断对错
def check_choose(choose_col):
    global score
    if choose_col == target_color:
        score += 1
        tip_text.set(f"✅ 正确！当前得分：{score}")
    else:
        tip_text.set(f"❌ 选错啦，正确颜色已标亮")
        # 把正确答案边框标红提示
        for btn in btn_list:
            if btn["bg"] == target_color:
                btn.config(highlightthickness=3, highlightbackground="red")
    # 1秒后下一题
    root.after(1000, new_round)

# 修改难度
def set_easy():
    global level
    level = 4
    score = 0
    tip_text.set("切换简单模式，分数清零")
    new_round()

def set_hard():
    global level
    level = 8
    score = 0
    tip_text.set("切换困难模式，分数清零")
    new_round()

# 顶部标题
tk.Label(root, text="🎨 配色眼力练习", font=("微软雅黑", 18, "bold")).pack(pady=10)

# 目标颜色展示画布
target_canvas = tk.Canvas(root, width=180, height=130)
target_canvas.pack(pady=8)

# 提示文字
tip_text = tk.StringVar()
tk.Label(root, textvariable=tip_text, font=("微软雅黑",12)).pack(pady=5)

# 选项按钮容器
btn_frame = tk.Frame(root)
btn_frame.pack(pady=10)

# 难度按钮
frame_diff = tk.Frame(root)
frame_diff.pack(pady=8)
tk.Button(frame_diff, text="简单(4选1)", command=set_easy, width=10).grid(row=0,column=0,padx=8)
tk.Button(frame_diff, text="困难(8选1)", command=set_hard, width=10).grid(row=0,column=1,padx=8)

# 初始化第一题
new_round()
root.mainloop()