from tkinter import Tk, Label, Entry, Button
import random

# 成语词库
idiom_data = [
    "一帆风顺", "十全十美", "美中不足", "足智多谋", "谋事在人",
    "人山人海", "海阔天空", "空穴来风", "风花雪月", "月下老人",
    "人定胜天", "天经地义", "义薄云天", "天高地厚", "厚积薄发",
    "发扬光大", "大起大落", "落井下石", "石沉大海", "海枯石烂"
]

class IdiomGame:
    def __init__(self, window):
        self.win = window
        self.win.title("成语接龙")
        self.win.geometry("520x350")

        self.now_char = ""  # 需要接续的首字

        # 界面组件
        Label(window, text="成语接龙小游戏", font=("黑体", 22)).pack(pady=10)

        self.lb_pc = Label(window, text="电脑：", font=("宋体", 15, "bold"))
        self.lb_pc.pack()

        self.lb_tip = Label(window, text="提示：", font=13, fg="blue")
        self.lb_tip.pack(pady=5)

        self.input_box = Entry(window, font=("宋体", 14), width=20)
        self.input_box.pack(pady=3)
        self.input_box.bind("<Return>", self.check)

        Button(window, text="提交", command=self.check, bg="#3498db", fg="white", font=12).pack(pady=5)

        self.lb_msg = Label(window, text="", font=13, fg="red")
        self.lb_msg.pack(pady=8)

        self.new_game()

    def get_first(self, s):
        return s[0]

    def get_last(self, s):
        return s[-1]

    # 电脑选词
    def pc_get_idiom(self, start_word):
        lst = [i for i in idiom_data if self.get_first(i) == start_word]
        if lst:
            return random.choice(lst)
        return None

    # 新开一局
    def new_game(self):
        pc_word = random.choice(idiom_data)
        self.now_char = self.get_last(pc_word)
        self.lb_pc.config(text=f"电脑：{pc_word}")
        self.lb_tip.config(text=f"请输入以【{self.now_char}】开头的成语")
        self.lb_msg.config(text="")
        self.input_box.delete(0, "end")

    # 校验输入
    def check(self, event=None):
        user_word = self.input_box.get().strip()
        # 输入错误
        if user_word not in idiom_data or self.get_first(user_word) != self.now_char:
            self.lb_msg.config(text="成语错误，本轮失败，即将重新开局！")
            self.win.after(2000, self.new_game)
            return

        # 电脑应答
        end_c = self.get_last(user_word)
        pc_new = self.pc_get_idiom(end_c)
        if not pc_new:
            self.lb_msg.config(text=f"电脑接不上！你获胜！你：{user_word}")
            self.win.after(2000, self.new_game)
            return

        self.lb_pc.config(text=f"电脑：{pc_new}")
        self.now_char = self.get_last(pc_new)
        self.lb_tip.config(text=f"请输入以【{self.now_char}】开头的成语")
        self.lb_msg.config(text=f"你的成语：{user_word}")
        self.input_box.delete(0, "end")

if __name__ == "__main__":
    root = Tk()
    game = IdiomGame(root)
    root.mainloop()