import tkinter as tk
from tkinter import ttk, messagebox

# 成语库（包含拼音首字/尾字，支持接龙校验）
IDIOMS = {
    "一帆风顺": {"first": "一", "last": "顺"},
    "顺理成章": {"first": "顺", "last": "章"},
    "章台杨柳": {"first": "章", "last": "柳"},
    "柳暗花明": {"first": "柳", "last": "明"},
    "明察秋毫": {"first": "明", "last": "毫"},
    "毫不在意": {"first": "毫", "last": "意"},
    "意气风发": {"first": "意", "last": "发"},
    "发扬光大": {"first": "发", "last": "大"},
    "大智若愚": {"first": "大", "last": "愚"},
    "愚公移山": {"first": "愚", "last": "山"},
    "山清水秀": {"first": "山", "last": "秀"},
    "秀外慧中": {"first": "秀", "last": "中"},
    "中庸之道": {"first": "中", "last": "道"},
    "道听途说": {"first": "道", "last": "说"},
    "说一不二": {"first": "说", "last": "二"},
    "二龙戏珠": {"first": "二", "last": "珠"},
    "珠联璧合": {"first": "珠", "last": "合"},
    "合二为一": {"first": "合", "last": "一"},
    "一心一意": {"first": "一", "last": "意"},
    "异想天开": {"first": "异", "last": "开"},
    "开门见山": {"first": "开", "last": "山"},
    "山穷水尽": {"first": "山", "last": "尽"},
    "尽善尽美": {"first": "尽", "last": "美"},
    "美中不足": {"first": "美", "last": "足"},
    "足智多谋": {"first": "足", "last": "谋"},
    "谋事在人": {"first": "谋", "last": "人"},
    "人山人海": {"first": "人", "last": "海"},
    "海阔天空": {"first": "海", "last": "空"},
    "空穴来风": {"first": "空", "last": "风"},
    "风调雨顺": {"first": "风", "last": "顺"}
}


class IdiomGame:
    def __init__(self, root):
        self.root = root
        self.root.title("成语接龙游戏")
        self.root.geometry("600x500")  # 窗口大小
        self.root.resizable(False, False)

        # 游戏初始化变量
        self.last_char = ""  # 上一个成语的最后一个字
        self.score = 0      # 玩家分数
        self.used_idioms = set()  # 已使用的成语

        # 创建界面组件
        self.create_widgets()
        # 游戏开始：电脑先手
        self.computer_first()

    def create_widgets(self):
        """创建GUI界面元素"""
        # 标题标签
        title_label = ttk.Label(self.root, text="成语接龙",
                                font=("微软雅黑", 20, "bold"))
        title_label.pack(pady=10)

        # 分数显示
        self.score_label = ttk.Label(
            self.root, text=f"当前分数：{self.score}", font=("微软雅黑", 14))
        self.score_label.pack()

        # 游戏记录区域
        ttk.Label(self.root, text="游戏记录：", font=("微软雅黑", 12)
                  ).pack(anchor="w", padx=20, pady=(10, 0))
        self.game_text = tk.Text(self.root, height=12,
                                 width=65, font=("微软雅黑", 11))
        self.game_text.pack(padx=20, pady=5)
        self.game_text.config(state=tk.DISABLED)  # 禁止编辑

        # 输入区域
        input_frame = ttk.Frame(self.root)
        input_frame.pack(pady=10)

        ttk.Label(input_frame, text="请输入成语：", font=(
            "微软雅黑", 12)).grid(row=0, column=0, padx=5)
        self.input_entry = ttk.Entry(input_frame, font=("微软雅黑", 12), width=20)
        self.input_entry.grid(row=0, column=1, padx=5)
        self.input_entry.focus()

        # 按钮
        submit_btn = ttk.Button(input_frame, text="提交",
                                command=self.check_player_idiom)
        submit_btn.grid(row=0, column=2, padx=5)
        restart_btn = ttk.Button(
            input_frame, text="重新开始", command=self.restart_game)
        restart_btn.grid(row=0, column=3, padx=5)

        # 规则提示
        rule_label = ttk.Label(
            self.root,
            text="规则：必须使用四字成语，首尾字相接，不可重复使用",
            font=("微软雅黑", 10),
            foreground="gray"
        )
        rule_label.pack(pady=10)

        # 绑定回车键提交
        self.input_entry.bind(
            "<Return>", lambda event: self.check_player_idiom())

    def add_log(self, text):
        """向游戏记录区域添加文字"""
        self.game_text.config(state=tk.NORMAL)
        self.game_text.insert(tk.END, text + "\n")
        self.game_text.see(tk.END)  # 自动滚动到底部
        self.game_text.config(state=tk.DISABLED)

    def computer_first(self):
        """电脑先手，随机出第一个成语"""
        import random
        first_idiom = random.choice(list(IDIOMS.keys()))
        self.last_char = IDIOMS[first_idiom]["last"]
        self.used_idioms.add(first_idiom)
        self.add_log(f"【电脑】：{first_idiom}")
        self.add_log(f"请你以【{self.last_char}】字开头接龙！")

    def check_player_idiom(self):
        """校验玩家输入的成语"""
        player_idiom = self.input_entry.get().strip()
        self.input_entry.delete(0, tk.END)

        # 输入校验
        if len(player_idiom) != 4:
            messagebox.showerror("错误", "请输入四字成语！")
            return

        if player_idiom not in IDIOMS:
            messagebox.showerror("错误", "该成语不在词库中，请重新输入！")
            return

        if player_idiom in self.used_idioms:
            messagebox.showerror("错误", "该成语已使用过，不能重复！")
            return

        # 接龙校验：首字必须等于上一个尾字
        first_char = IDIOMS[player_idiom]["first"]
        if first_char != self.last_char:
            messagebox.showerror("错误", f"接龙失败！必须以【{self.last_char}】开头！")
            return

        # 玩家回答正确
        self.used_idioms.add(player_idiom)
        self.score += 10
        self.score_label.config(text=f"当前分数：{self.score}")
        self.add_log(f"【你】：{player_idiom}")

        # 电脑接龙
        self.computer_answer(player_idiom)

    def computer_answer(self, player_idiom):
        """电脑根据玩家成语自动接龙"""
        player_last = IDIOMS[player_idiom]["last"]
        # 查找可用成语
        candidates = [
            idiom for idiom, info in IDIOMS.items()
            if info["first"] == player_last and idiom not in self.used_idioms
        ]

        if not candidates:
            self.add_log("【电脑】：我接不上来了！你赢了！🎉")
            messagebox.showinfo("游戏结束", f"恭喜你获胜！最终得分：{self.score}")
            return

        # 电脑随机选择一个成语
        import random
        computer_idiom = random.choice(candidates)
        self.used_idioms.add(computer_idiom)
        self.last_char = IDIOMS[computer_idiom]["last"]
        self.add_log(f"【电脑】：{computer_idiom}")
        self.add_log(f"请你以【{self.last_char}】字开头接龙！")

    def restart_game(self):
        """重新开始游戏"""
        self.last_char = ""
        self.score = 0
        self.used_idioms.clear()
        self.score_label.config(text=f"当前分数：{self.score}")
        self.game_text.config(state=tk.NORMAL)
        self.game_text.delete(1.0, tk.END)
        self.game_text.config(state=tk.DISABLED)
        self.add_log("======== 游戏重新开始 ========")
        self.computer_first()


# 启动游戏
if __name__ == "__main__":
    root = tk.Tk()
    app = IdiomGame(root)
    root.mainloop()
