import tkinter as tk
import random

# 🌟 扩充版题库：20道经典脑筋急转弯
RIDDLES = [
    {"q": "什么东西越洗越脏？", "a": "水"},
    {"q": "有头没有颈，身上冷冰冰，有翅不能飞，无脚也能行。", "a": "鱼"},
    {"q": "什么东西天气越热，它爬得越高？", "a": "温度计"},
    {"q": "一个人掉进河里，为什么头发没有湿？", "a": "因为他是光头"},
    {"q": "什么门永远关不上？", "a": "球门"},
    {"q": "什么东西打破了，大家反而很高兴？", "a": "世界纪录"},
    {"q": "一只公鸡在金字塔顶端下蛋，蛋会掉向哪边？", "a": "公鸡不下蛋"},
    {"q": "什么书在书店买不到？", "a": "遗书"},
    {"q": "偷什么东西不犯法？", "a": "偷笑"},
    {"q": "什么东西有头没有脚？", "a": "砖头"},
    {"q": "什么蛋打不烂，煮不熟，更不能吃？", "a": "考试得的零蛋"},
    {"q": "小明在考试，为什么一直看别人的试卷？", "a": "因为他是监考老师"},
    {"q": "哪一个月有二十八天？", "a": "每个月都有"},
    {"q": "一只蚂蚁从泰山上掉下来，为什么没有摔死？", "a": "因为它被风吹走了"},
    {"q": "什么东西越热越爱出来？", "a": "汗"},
    {"q": "什么东西属于你，但别人用的比你多？", "a": "你的名字"},
    {"q": "什么车寸步难行？", "a": "风车"},
    {"q": "为什么大雁秋天要飞到南方去？", "a": "因为走过去太慢了"},
    {"q": "小明总是喜欢把闹钟调快，为什么？", "a": "因为他怕迟到"},
    {"q": "什么水永远用不完？", "a": "口水"}
]

class CartoonRiddleApp:
    def __init__(self, root):
        self.root = root
        self.root.title("🎈 脑筋急转弯大挑战")
        self.root.geometry("520x480")
        self.root.resizable(False, False)
        
        # 🎨 卡通配色
        self.bg_color = "#FFF9E6"
        self.root.configure(bg=self.bg_color)
        
        # 游戏状态变量
        self.score = 0
        self.time_left = 10
        self.current_riddle = None
        self.timer_id = None
        self.used_indices = []  # 记录已出的题目，防止重复
        
        # --- 顶部状态栏（分数 & 倒计时） ---
        top_frame = tk.Frame(root, bg=self.bg_color)
        top_frame.pack(pady=(20, 10), padx=20, fill="x")
        
        self.score_label = tk.Label(
            top_frame, text="🏆 分数：0", font=("Microsoft YaHei", 16, "bold"), 
            bg="#FFD54F", fg="#E65100", padx=15, pady=5, relief="groove", bd=2
        )
        self.score_label.pack(side="left")
        
        self.time_label = tk.Label(
            top_frame, text="⏳ 倒计时：30秒", font=("Microsoft YaHei", 16, "bold"), 
            bg="#81D4FA", fg="#01579B", padx=15, pady=5, relief="groove", bd=2
        )
        self.time_label.pack(side="right")
        
        # --- 标题 ---
        title_label = tk.Label(
            root, text="🎲 脑筋急转弯大挑战", font=("Comic Sans MS", 22, "bold"), 
            bg=self.bg_color, fg="#FF6347"
        )
        title_label.pack(pady=(5, 15))
        
        # --- 题目显示区 ---
        self.q_label = tk.Label(
            root, text="点击「🔄 换一题」开始挑战吧！", 
            font=("Microsoft YaHei", 16), bg="#E0F7FA", fg="#00796B", 
            wraplength=440, justify="center", padx=10, pady=20, relief="groove", bd=2
        )
        self.q_label.pack(pady=10, padx=20)
        
        # --- 输入框与提交按钮 ---
        input_frame = tk.Frame(root, bg=self.bg_color)
        input_frame.pack(pady=15)
        
        self.input_entry = tk.Entry(
            input_frame, font=("Microsoft YaHei", 15), width=20, 
            justify="center", relief="solid", bd=2, fg="#333333"
        )
        self.input_entry.pack(side="left", padx=(0, 10), ipady=6)
        self.input_entry.bind("<Return>", lambda event: self.check_answer())
        
        self.submit_btn = tk.Button(
            input_frame, text="💡 提交", font=("Microsoft YaHei", 13, "bold"),
            bg="#FFB74D", fg="white", activebackground="#FFA726",
            relief="flat", padx=15, pady=5, cursor="hand2",
            command=self.check_answer
        )
        self.submit_btn.pack(side="left")
        
        # --- 答案反馈区 ---
        self.feedback_label = tk.Label(
            root, text="", font=("Microsoft YaHei", 15, "bold"), 
            bg=self.bg_color, wraplength=440, justify="center"
        )
        self.feedback_label.pack(pady=10)
        
        # --- 换一题按钮 ---
        self.next_btn = tk.Button(
            root, text="🔄 换一题", font=("Microsoft YaHei", 14, "bold"),
            bg="#81C784", fg="white", activebackground="#66BB6A",
            relief="flat", padx=25, pady=8, cursor="hand2",
            command=self.show_question
        )
        self.next_btn.pack(pady=15)

    def start_timer(self):
        """启动倒计时"""
        # 清除可能存在的旧定时器
        if self.timer_id:
            self.root.after_cancel(self.timer_id)
            
        self.time_left = 10
        self.update_time_display()
        self.countdown()

    def countdown(self):
        """倒计时逻辑"""
        if self.time_left > 0:
            self.time_left -= 1
            self.update_time_display()
            self.timer_id = self.root.after(1000, self.countdown)
        else:
            # 时间到，自动判错并显示答案
            self.feedback_label.config(text=f"⏰ 时间到！正确答案是：【{self.current_riddle['a']}】", fg="#F44336")

    def update_time_display(self):
        """更新倒计时UI"""
        self.time_label.config(text=f"⏳ 倒计时：{self.time_left}秒")
        # 剩下3秒时变红警告
        if self.time_left <= 3:
            self.time_label.config(bg="#FFCDD2", fg="#C62828")
        else:
            self.time_label.config(bg="#81D4FA", fg="#01579B")

    def show_question(self):
        """随机抽取并显示题目（防重复）"""
        # 如果所有题目都出完了，重置题库
        if len(self.used_indices) == len(RIDDLES):
            self.used_indices.clear()
            
        # 随机抽取一个没出过的题目
        while True:
            index = random.randint(0, len(RIDDLES) - 1)
            if index not in self.used_indices:
                self.used_indices.append(index)
                self.current_riddle = RIDDLES[index]
                break
                
        self.q_label.config(text=self.current_riddle["q"])
        self.feedback_label.config(text="")
        self.input_entry.delete(0, tk.END)
        self.input_entry.focus()
        
        # 启动倒计时
        self.start_timer()

    def check_answer(self):
        """判断用户输入的答案"""
        if not self.current_riddle:
            self.feedback_label.config(text="⚠️ 请先点击「换一题」哦！", fg="#FF9800")
            return
            
        user_ans = self.input_entry.get().strip()
        correct_ans = self.current_riddle["a"]
        
        # 停止倒计时
        if self.timer_id:
            self.root.after_cancel(self.timer_id)
            
        if user_ans == correct_ans:
            self.score += 10
            self.score_label.config(text=f"🏆 分数：{self.score}")
            self.feedback_label.config(text="🎉 哇！你太聪明啦，答对咯！+10分", fg="#4CAF50")
        else:
            self.feedback_label.config(text=f"😅 哎呀，答错啦！正确答案是：【{correct_ans}】", fg="#F44336")

if __name__ == "__main__":
    root = tk.Tk()
    app = CartoonRiddleApp(root)
    root.mainloop()