import tkinter as tk
from tkinter import ttk, messagebox
import random
import time

class TypingTest:
    def __init__(self, root):
        self.root = root
        self.root.title("005. 打字练习软件")
        self.root.geometry("700x500")
        self.root.resizable(False, False)
        
        # 练习文本库
        self.texts = [
            "The quick brown fox jumps over the lazy dog.",
            "Python is a powerful programming language.",
            "Practice makes perfect in typing skills.",
            "Hello world! This is a typing test program.",
            "Computer science is the future of technology.",
            "Keep calm and continue learning every day.",
            "Success is the result of hard work and dedication.",
            "Artificial intelligence will change the world.",
        ]
        
        self.current_text = ""
        self.start_time = None
        self.is_testing = False
        self.correct_chars = 0
        self.total_chars = 0
        
        self.setup_ui()
        self.new_test()
    
    def setup_ui(self):
        # 标题
        title = tk.Label(self.root, text="⌨️ 打字练习软件", 
                        font=("微软雅黑", 20, "bold"), fg="#333")
        title.pack(pady=15)
        
        # 练习文本显示区
        self.text_frame = tk.Frame(self.root, relief=tk.SUNKEN, bd=2)
        self.text_frame.pack(pady=10, padx=20, fill=tk.BOTH)
        
        self.text_label = tk.Label(self.text_frame, text="", 
                                  font=("Consolas", 14), 
                                  wraplength=650, justify=tk.LEFT,
                                  padx=15, pady=15, bg="white", anchor="nw")
        self.text_label.pack(fill=tk.BOTH, expand=True)
        
        # 输入区
        input_frame = tk.Frame(self.root)
        input_frame.pack(pady=10, padx=20, fill=tk.X)
        
        tk.Label(input_frame, text="开始输入：", font=("微软雅黑", 11)).pack(side=tk.LEFT)
        self.entry = tk.Entry(input_frame, font=("Consolas", 14), 
                             relief=tk.SUNKEN, bd=2)
        self.entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
        self.entry.bind("<KeyRelease>", self.on_key_release)
        self.entry.bind("<Return>", self.check_result)
        
        # 按钮区
        btn_frame = tk.Frame(self.root)
        btn_frame.pack(pady=10)
        
        self.start_btn = tk.Button(btn_frame, text="开始练习", width=12,
                                   bg="#4CAF50", fg="white", font=("微软雅黑", 11),
                                   command=self.start_test)
        self.start_btn.pack(side=tk.LEFT, padx=5)
        
        tk.Button(btn_frame, text="新题目", width=12,
                  bg="#2196F3", fg="white", font=("微软雅黑", 11),
                  command=self.new_test).pack(side=tk.LEFT, padx=5)
        
        tk.Button(btn_frame, text="退出", width=12,
                  bg="#f44336", fg="white", font=("微软雅黑", 11),
                  command=self.root.quit).pack(side=tk.LEFT, padx=5)
        
        # 统计信息区
        stats_frame = tk.LabelFrame(self.root, text="📊 统计信息", 
                                    font=("微软雅黑", 11), padx=15, pady=10)
        stats_frame.pack(pady=15, padx=20, fill=tk.X)
        
        # 使用网格布局
        self.time_label = tk.Label(stats_frame, text="用时：0 秒", 
                                   font=("Consolas", 11))
        self.time_label.grid(row=0, column=0, padx=20)
        
        self.speed_label = tk.Label(stats_frame, text="速度：0 字/分钟", 
                                    font=("Consolas", 11))
        self.speed_label.grid(row=0, column=1, padx=20)
        
        self.accuracy_label = tk.Label(stats_frame, text="正确率：100%", 
                                       font=("Consolas", 11))
        self.accuracy_label.grid(row=0, column=2, padx=20)
        
        self.errors_label = tk.Label(stats_frame, text="错误：0 个", 
                                     font=("Consolas", 11))
        self.errors_label.grid(row=0, column=3, padx=20)
        
        # 提示标签
        self.hint_label = tk.Label(self.root, text="💡 点击「开始练习」后开始计时", 
                                   font=("微软雅黑", 10), fg="gray")
        self.hint_label.pack(pady=5)
    
    def new_test(self):
        """生成新题目"""
        self.current_text = random.choice(self.texts)
        self.text_label.config(text=self.current_text)
        self.entry.delete(0, tk.END)
        self.entry.config(state="disabled")
        self.is_testing = False
        self.start_time = None
        self.correct_chars = 0
        self.total_chars = 0
        self.start_btn.config(text="开始练习")
        self.update_stats()
        self.hint_label.config(text="💡 点击「开始练习」后开始计时")
    
    def start_test(self):
        """开始测试"""
        self.entry.config(state="normal")
        self.entry.focus()
        self.start_time = time.time()
        self.is_testing = True
        self.start_btn.config(state="disabled")
        self.hint_label.config(text="⌨️ 正在计时中... 按 Enter 提交结果")
        self.update_timer()
    
    def update_timer(self):
        """更新计时器"""
        if self.is_testing:
            elapsed = int(time.time() - self.start_time)
            self.time_label.config(text=f"用时：{elapsed} 秒")
            self.root.after(1000, self.update_timer)
    
    def on_key_release(self, event):
        """实时检查输入"""
        if not self.is_testing:
            return
        
        user_input = self.entry.get()
        target = self.current_text[:len(user_input)]
        
        # 高亮显示对错
        if user_input:
            if user_input[-1] == target[-1]:
                self.correct_chars += 1
            self.total_chars = len(user_input)
        
        self.update_stats()
    
    def update_stats(self):
        """更新统计信息"""
        if self.start_time and self.is_testing:
            elapsed = time.time() - self.start_time
            if elapsed > 0:
                wpm = int((self.correct_chars / elapsed) * 60)
                self.speed_label.config(text=f"速度：{wpm} 字/分钟")
        
        if self.total_chars > 0:
            accuracy = (self.correct_chars / self.total_chars) * 100
            self.accuracy_label.config(text=f"正确率：{accuracy:.1f}%")
            self.errors_label.config(text=f"错误：{self.total_chars - self.correct_chars} 个")
    
    def check_result(self, event=None):
        """检查最终结果"""
        if not self.is_testing:
            return
        
        user_input = self.entry.get()
        elapsed = time.time() - self.start_time
        
        # 计算最终结果
        correct = sum(1 for a, b in zip(user_input, self.current_text) if a == b)
        total = len(user_input)
        accuracy = (correct / len(self.current_text)) * 100 if self.current_text else 0
        wpm = int((correct / elapsed) * 60) if elapsed > 0 else 0
        
        # 显示结果
        result = f"📝 测试结果\n\n"
        result += f"用时：{int(elapsed)} 秒\n"
        result += f"速度：{wpm} 字/分钟\n"
        result += f"正确率：{accuracy:.1f}%\n"
        result += f"正确字符：{correct}/{len(self.current_text)}"
        
        messagebox.showinfo("测试结果", result)
        
        self.is_testing = False
        self.entry.config(state="disabled")
        self.start_btn.config(state="normal", text="重新开始")

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