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

# ================== 成语词库（精简版，实际可换成大词典） ==================
IDIOMS = [
    "一心一意", "意气风发", "发愤图强", "强词夺理",
    "理直气壮", "壮志凌云", "云开见日", "日新月异",
    "异想天开", "开门见山", "山清水秀", "秀外慧中",
    "中流砥柱", "柱石之坚", "坚不可摧", "摧枯拉朽",
    "朽木不雕", "雕虫小技", "技高一筹", "筹谋划策",
    "策马奔腾", "腾云驾雾", "雾里看花", "花好月圆",
    "圆圆满满", "满面春风", "风平浪静", "静极思动",
    "动人心弦", "弦外之音", "音容笑貌", "貌合神离",
    "离经叛道", "道听途说", "说一不二", "二话不说",
    "三五成群", "群策群力", "力争上游", "游刃有余"
]

PINYIN_MAP = {}
for idiom in IDIOMS:
    last_char = idiom[-1]
    pin = pypinyin.lazy_pinyin(last_char, style=pypinyin.NORMAL)[0]
    PINYIN_MAP.setdefault(pin, []).append(idiom)


class IdiomSolitaire:
    def __init__(self, root):
        self.root = root
        self.root.title("011. 成语接龙")
        self.root.geometry("520x420")
        self.root.resizable(False, False)

        self.history = []
        self.current_idiom = ""

        self.setup_ui()
        self.start_game()

    def setup_ui(self):
        # 标题
        tk.Label(
            self.root, text="🀄 成语接龙",
            font=("微软雅黑", 20, "bold")
        ).pack(pady=10)

        # 当前成语
        self.label_current = tk.Label(
            self.root, text="",
            font=("楷体", 26, "bold"), fg="#d32f2f"
        )
        self.label_current.pack(pady=5)

        # 输入区
        frame_input = tk.Frame(self.root)
        frame_input.pack(pady=10)

        tk.Label(frame_input, text="你的成语：").pack(side=tk.LEFT)
        self.entry = tk.Entry(frame_input, font=("楷体", 18), width=12)
        self.entry.pack(side=tk.LEFT)
        self.entry.bind("<Return>", lambda e: self.check())

        tk.Button(
            frame_input, text="确定",
            command=self.check, bg="#4CAF50", fg="white"
        ).pack(side=tk.LEFT, padx=5)

        # 提示
        self.label_tip = tk.Label(
            self.root, text="提示：回车提交，空格键获取提示",
            font=("微软雅黑", 9), fg="gray"
        )
        self.label_tip.pack()

        # 历史记录
        tk.Label(
            self.root, text="—— 接龙记录 ——",
            font=("微软雅黑", 10)
        ).pack(pady=(10, 0))

        self.text_history = tk.Text(
            self.root, height=8, width=45,
            font=("Consolas", 10),
            state=tk.DISABLED
        )
        self.text_history.pack()

        # 按钮区
        btn_frame = tk.Frame(self.root)
        btn_frame.pack(pady=8)

        tk.Button(
            btn_frame, text="提示一个",
            command=self.hint
        ).pack(side=tk.LEFT, padx=5)

        tk.Button(
            btn_frame, text="重新开始",
            command=self.start_game
        ).pack(side=tk.LEFT, padx=5)

        tk.Button(
            btn_frame, text="退出",
            command=self.root.quit
        ).pack(side=tk.LEFT, padx=5)

        self.root.bind("<space>", lambda e: self.hint())

    def start_game(self):
        self.history.clear()
        self.current_idiom = random.choice(IDIOMS)
        self.update_ui()

    def update_ui(self):
        self.label_current.config(text=self.current_idiom)
        self.entry.delete(0, tk.END)

        self.text_history.config(state=tk.NORMAL)
        self.text_history.delete("1.0", tk.END)
        for item in self.history[-10:]:
            self.text_history.insert(tk.END, item + "\n")
        self.text_history.config(state=tk.DISABLED)

    def check(self):
        user = self.entry.get().strip()
        if len(user) != 4:
            messagebox.showwarning("格式错误", "请输入四个字的成语！")
            return

        if user not in IDIOMS:
            messagebox.showerror("不存在", f"“{user}”不在词库中！")
            return

        if user in self.history:
            messagebox.showwarning("重复", "这个成语已经用过了！")
            return

        last_pin = pypinyin.lazy_pinyin(
            self.current_idiom[-1], style=pypinyin.NORMAL
        )[0]
        first_pin = pypinyin.lazy_pinyin(
            user[0], style=pypinyin.NORMAL
        )[0]

        if first_pin != last_pin:
            messagebox.showerror(
                "接龙失败",
                f"“{user}”首字拼音({first_pin})与"
                f"“{self.current_idiom}”尾字拼音({last_pin})不匹配！"
            )
            return

        # 成功
        self.history.append(f"{self.current_idiom} → {user}")
        self.current_idiom = user
        self.update_ui()

    def hint(self):
        last_char = self.current_idiom[-1]
        pin = pypinyin.lazy_pinyin(last_char, style=pypinyin.NORMAL)[0]
        candidates = PINYIN_MAP.get(pin, [])

        # 排除历史
        candidates = [c for c in candidates if c not in self.history]

        if candidates:
            tip = random.choice(candidates)
            messagebox.showinfo("提示", f"你可以试试：“{tip}”")
        else:
            messagebox.showwarning("提示", "词库里找不到合适的成语了，换一个吧！")
            self.start_game()


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