import tkinter as tk
from tkinter import ttk, messagebox
import random
import time

# 纯英文练习文本库（不同难度的经典段落）
PRACTICE_TEXT = [
    "The quick brown fox jumps over the lazy dog. This sentence contains every letter in the English alphabet.",
    "Programming is the art of telling another human being what one wants the computer to do. Learning to code is a valuable skill in today's digital world.",
    "Python is a high-level, general-purpose programming language known for its readability and simplicity. It is widely used in web development, data science, and artificial intelligence.",
    "Consistency is key when learning to type. Practicing for just 15 minutes every day will significantly improve your speed and accuracy over time.",
    "The only way to learn a new programming language is by writing programs in it. Start small and gradually take on more complex projects to build your skills.",
    "In the middle of difficulty lies opportunity. Every challenge you face while learning to code is a chance to grow and improve your problem-solving abilities.",
    "Technology is best when it brings people together. Coding is not just about machines, it's about creating tools that make people's lives better.",
    "Learning to type quickly and accurately is essential for programmers, writers, and anyone who works with computers on a daily basis. Mastery comes with practice and patience.",
    "Data is the new oil of the digital economy. Being able to process, analyze, and interpret data is one of the most important skills you can develop today.",
    "Success is not final, failure is not fatal: it is the courage to continue that counts. Keep practicing, keep learning, and never give up on your goals."
]


class TypingPracticeApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Python 英文打字练习器")
        self.root.geometry("800x600")
        self.root.resizable(False, False)

        # 初始化变量
        self.practice_text = ""  # 当前练习文本
        self.start_time = None   # 开始时间
        self.is_practicing = False  # 是否正在练习
        self.user_input = ""     # 用户输入内容

        # 创建界面组件
        self.create_widgets()

        # 加载初始练习文本
        self.load_new_text()

    def create_widgets(self):
        # 标题标签
        title_label = ttk.Label(
            self.root,
            text="Python 英文打字练习器",
            font=("Arial", 20, "bold")
        )
        title_label.pack(pady=20)

        # 练习文本显示框
        self.text_display = tk.Text(
            self.root,
            width=80,
            height=5,
            font=("Arial", 12),
            wrap=tk.WORD,
            state=tk.DISABLED,
            bg="#f0f0f0"
        )
        self.text_display.pack(pady=10, padx=20)

        # 统计信息框架
        stats_frame = ttk.Frame(self.root)
        stats_frame.pack(pady=10, padx=20, fill=tk.X)

        # 速度显示
        ttk.Label(stats_frame, text="Typing Speed:", font=(
            "Arial", 10)).grid(row=0, column=0, padx=5)
        self.speed_label = ttk.Label(
            stats_frame, text="0 WPM", font=("Arial", 10))
        self.speed_label.grid(row=0, column=1, padx=5)

        # 准确率显示
        ttk.Label(stats_frame, text="Accuracy:", font=(
            "Arial", 10)).grid(row=0, column=2, padx=5)
        self.accuracy_label = ttk.Label(
            stats_frame, text="100%", font=("Arial", 10))
        self.accuracy_label.grid(row=0, column=3, padx=5)

        # 正确/错误字符数
        ttk.Label(stats_frame, text="Correct/Errors:",
                  font=("Arial", 10)).grid(row=0, column=4, padx=5)
        self.char_label = ttk.Label(
            stats_frame, text="0/0", font=("Arial", 10))
        self.char_label.grid(row=0, column=5, padx=5)

        # 用户输入框
        self.input_entry = tk.Text(
            self.root,
            width=80,
            height=8,
            font=("Arial", 12),
            wrap=tk.WORD
        )
        self.input_entry.pack(pady=10, padx=20)
        self.input_entry.bind("<KeyRelease>", self.on_key_press)

        # 按钮框架
        btn_frame = ttk.Frame(self.root)
        btn_frame.pack(pady=20)

        # 新文本按钮
        self.new_text_btn = ttk.Button(
            btn_frame,
            text="New Text",
            command=self.load_new_text,
            width=15
        )
        self.new_text_btn.grid(row=0, column=0, padx=10)

        # 重置按钮
        self.reset_btn = ttk.Button(
            btn_frame,
            text="Reset",
            command=self.reset_practice,
            width=15
        )
        self.reset_btn.grid(row=0, column=1, padx=10)

    def load_new_text(self):
        """加载新的随机练习文本"""
        self.practice_text = random.choice(PRACTICE_TEXT)
        self.text_display.config(state=tk.NORMAL)
        self.text_display.delete(1.0, tk.END)
        self.text_display.insert(1.0, self.practice_text)
        self.text_display.config(state=tk.DISABLED)
        self.reset_practice()

    def reset_practice(self):
        """重置练习状态"""
        self.input_entry.delete(1.0, tk.END)
        self.start_time = None
        self.is_practicing = False
        self.user_input = ""
        self.speed_label.config(text="0 WPM")
        self.accuracy_label.config(text="100%")
        self.char_label.config(text="0/0")

    def on_key_press(self, event):
        """按键释放事件处理"""
        # 开始计时（第一次输入时）
        if not self.is_practicing and self.input_entry.get(1.0, tk.END).strip():
            self.start_time = time.time()
            self.is_practicing = True

        # 获取用户输入（去除最后的换行符）
        self.user_input = self.input_entry.get(1.0, tk.END)[:-1]

        # 计算统计数据
        self.calculate_stats()

        # 检查是否完成输入
        self.check_completion()

    def calculate_stats(self):
        """计算打字速度和准确率"""
        if not self.is_practicing or self.start_time is None:
            return

        # 计算耗时（秒）
        elapsed_time = time.time() - self.start_time
        if elapsed_time < 1:  # 避免除以0
            return

        # 统计正确/错误字符数
        correct_chars = 0
        error_chars = 0
        total_chars = min(len(self.user_input), len(self.practice_text))

        for i in range(total_chars):
            if self.user_input[i] == self.practice_text[i]:
                correct_chars += 1
            else:
                error_chars += 1

        # 计算准确率
        if total_chars > 0:
            accuracy = (correct_chars / total_chars) * 100
        else:
            accuracy = 100

        # 计算打字速度（WPM，每分钟单词数，按每个单词5个字符计算）
        words_typed = correct_chars / 5
        wpm = (words_typed / elapsed_time) * 60

        # 更新显示
        self.speed_label.config(text=f"{round(wpm, 1)} WPM")
        self.accuracy_label.config(text=f"{round(accuracy, 1)}%")
        self.char_label.config(text=f"{correct_chars}/{error_chars}")

    def check_completion(self):
        """检查是否完成全部文本输入"""
        if self.user_input == self.practice_text:
            # 计算最终统计数据
            elapsed_time = time.time() - self.start_time
            total_chars = len(self.practice_text)
            correct_chars = total_chars
            accuracy = 100.0
            words_typed = correct_chars / 5
            wpm = (words_typed / elapsed_time) * 60

            # 显示完成提示
            messagebox.showinfo(
                "Practice Complete!",
                f"🎉 Congratulations!\n\nTime: {elapsed_time:.2f} seconds\nSpeed: {wpm:.1f} WPM\nAccuracy: {accuracy:.1f}%\nTotal Characters: {total_chars}"
            )

            # 重置练习
            self.reset_practice()


if __name__ == "__main__":
    root = tk.Tk()
    app = TypingPracticeApp(root)
    root.mainloop()
