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

# 打字练习核心类
class TypingTrainer:
    def __init__(self, root):
        self.root = root
        self.root.title("打字练习软件")
        self.root.geometry("800x500")  # 窗口大小
        self.root.resizable(False, False)

        # 练习文本库（可自行添加）
        self.text_library = [
            "Python is a powerful programming language.",
            "Practice makes perfect, keep typing every day.",
            "The quick brown fox jumps over the lazy dog.",
            "Hello world, welcome to the typing practice tool.",
            "Success comes from hard work and persistence.",
            "我喜欢编程，Python 让开发变得简单有趣。",
            "坚持练习打字，提高效率，享受指尖飞舞的感觉。",
            "知识改变命运，学习成就未来。"
        ]

        # 变量初始化
        self.current_text = ""  # 当前练习文本
        self.start_time = 0     # 开始时间
        self.is_typing = False  # 是否正在练习
        self.correct_count = 0  # 正确字数
        self.error_count = 0    # 错误字数

        # 创建界面组件
        self.create_widgets()

    # 创建界面
    def create_widgets(self):
        # 样式设置
        style = ttk.Style()
        style.configure("TLabel", font=("微软雅黑", 12))
        style.configure("TButton", font=("微软雅黑", 11))

        # 标题
        title_label = ttk.Label(self.root, text="打字练习软件", font=("微软雅黑", 18, "bold"))
        title_label.pack(pady=10)

        # 统计信息框架
        stats_frame = ttk.Frame(self.root)
        stats_frame.pack(pady=5, fill=tk.X, padx=20)

        self.time_label = ttk.Label(stats_frame, text="用时：0 秒")
        self.time_label.grid(row=0, column=0, padx=10)

        self.correct_label = ttk.Label(stats_frame, text="正确：0 字")
        self.correct_label.grid(row=0, column=1, padx=10)

        self.error_label = ttk.Label(stats_frame, text="错误：0 字")
        self.error_label.grid(row=0, column=2, padx=10)

        self.wpm_label = ttk.Label(stats_frame, text="速度：0 WPM")
        self.wpm_label.grid(row=0, column=3, padx=10)

        # 待输入文本框
        self.text_label = tk.Label(
            self.root, 
            text="点击【开始练习】开始打字", 
            font=("微软雅黑", 14),
            wraplength=700,
            justify=tk.LEFT
        )
        self.text_label.pack(pady=15, padx=20, fill=tk.BOTH)

        # 输入框
        self.input_entry = tk.Entry(
            self.root,
            font=("微软雅黑", 14),
            state=tk.DISABLED  # 默认禁用
        )
        self.input_entry.pack(pady=10, padx=20, fill=tk.X)
        self.input_entry.bind("<KeyRelease>", self.check_text)  # 按键释放时检查

        # 按钮框架
        btn_frame = ttk.Frame(self.root)
        btn_frame.pack(pady=20)

        self.start_btn = ttk.Button(btn_frame, text="开始练习", command=self.start_typing)
        self.start_btn.grid(row=0, column=0, padx=15)

        self.reset_btn = ttk.Button(btn_frame, text="重置", command=self.reset_typing)
        self.reset_btn.grid(row=0, column=1, padx=15)

    # 开始练习
    def start_typing(self):
        # 随机选择文本
        self.current_text = random.choice(self.text_library)
        self.text_label.config(text=self.current_text, fg="black")
        
        # 重置状态
        self.input_entry.config(state=tk.NORMAL)
        self.input_entry.delete(0, tk.END)
        self.input_entry.focus()  # 自动聚焦输入框
        
        self.start_time = time.time()
        self.is_typing = True
        self.correct_count = 0
        self.error_count = 0
        
        self.update_stats()
        self.start_btn.config(state=tk.DISABLED)

    # 检查输入是否正确
    def check_text(self, event):
        if not self.is_typing:
            return

        user_input = self.input_entry.get()
        correct_text = self.current_text[:len(user_input)]

        # 统计对错
        self.correct_count = 0
        self.error_count = 0
        for i, char in enumerate(user_input):
            if i < len(self.current_text) and char == self.current_text[i]:
                self.correct_count += 1
            else:
                self.error_count += 1

        # 颜色提示：正确绿色，错误红色
        if user_input == correct_text:
            self.text_label.config(fg="green")
        else:
            self.text_label.config(fg="red")

        # 完成练习
        if user_input == self.current_text:
            self.is_typing = False
            self.input_entry.config(state=tk.DISABLED)
            self.start_btn.config(state=tk.NORMAL)
            total_time = round(time.time() - self.start_time, 1)
            wpm = round(self.correct_count / total_time * 60) if total_time > 0 else 0
            messagebox.showinfo(
                "练习完成",
                f"用时：{total_time} 秒\n正确：{self.correct_count} 字\n错误：{self.error_count} 字\n打字速度：{wpm} WPM"
            )

        self.update_stats()

    # 更新统计信息
    def update_stats(self):
        if self.is_typing:
            elapsed_time = round(time.time() - self.start_time, 1)
            wpm = round(self.correct_count / elapsed_time * 60) if elapsed_time > 0 else 0
        else:
            elapsed_time = 0
            wpm = 0

        self.time_label.config(text=f"用时：{elapsed_time} 秒")
        self.correct_label.config(text=f"正确：{self.correct_count} 字")
        self.error_label.config(text=f"错误：{self.error_count} 字")
        self.wpm_label.config(text=f"速度：{wpm} WPM")

    # 重置练习
    def reset_typing(self):
        self.is_typing = False
        self.input_entry.config(state=tk.DISABLED)
        self.text_label.config(text="点击【开始练习】开始打字", fg="black")
        self.start_btn.config(state=tk.NORMAL)
        self.correct_count = 0
        self.error_count = 0
        self.update_stats()

# 运行程序
if __name__ == "__main__":
    window = tk.Tk()
    app = TypingTrainer(window)
    window.mainloop()