import tkinter as tk
from tkinter import ttk, messagebox, font
import random
import time
from collections import deque
import json
from pathlib import Path

class CartoonIdiomGame:
    def __init__(self, root):
        self.root = root
        self.root.title("🎮 卡通成语接龙大冒险 🎮")
        self.root.geometry("900x700")
        
        # 设置卡通风格颜色
        self.colors = {
            'bg': '#FFF5E1',  # 米黄色背景
            'primary': '#FF6B8B',  # 粉色
            'secondary': '#4ECDC4',  # 青色
            'accent': '#FFD166',  # 黄色
            'success': '#06D6A0',  # 绿色
            'warning': '#FF9E6D',  # 橙色
            'text': '#2D3047',  # 深蓝色
            'frame': '#FFE8D6',  # 浅橙色
            'player': '#A7C5EB',  # 浅蓝色
            'computer': '#FFAAA5'  # 浅粉色
        }
        
        # 卡通字体
        self.title_font = ("Comic Sans MS", 24, "bold")
        self.heading_font = ("Comic Sans MS", 16, "bold")
        self.normal_font = ("Arial Rounded MT Bold", 12)
        self.idiom_font = ("Microsoft YaHei", 20, "bold")
        self.button_font = ("Arial Rounded MT Bold", 11)
        
        # 成语数据库（扩展版）
        self.idioms = self.load_idioms()
        self.used_idioms = set()
        
        # 游戏状态
        self.score = 0
        self.combo = 0
        self.max_combo = 0
        self.current_idiom = ""
        self.game_active = False
        self.player_turn = True
        
        # 角色和皮肤
        self.player_skin = "🐱"
        self.computer_skin = "🤖"
        self.skins = {
            "🐱": "猫咪小智",
            "🐶": "狗狗阿福",
            "🐰": "兔子蹦蹦", 
            "🐼": "熊猫胖达",
            "🦊": "狐狸小机灵",
            "🦁": "狮子大王"
        }
        
        # 初始化UI
        self.setup_ui()
        self.create_home_screen()
        
    def load_idioms(self):
        """加载成语数据库"""
        idioms = [
            "一马当先", "先发制人", "人山人海", "海阔天空", "空穴来风",
            "风花雪月", "月明星稀", "稀奇古怪", "怪力乱神", "神采飞扬",
            "扬眉吐气", "气宇轩昂", "昂首阔步", "步步高升", "升堂入室",
            "十全十美", "美中不足", "足智多谋", "谋事在人", "人定胜天",
            "天长地久", "久别重逢", "逢凶化吉", "吉人天相", "相安无事",
            "事在人为", "为人师表", "表里如一", "一帆风顺", "顺水推舟",
            "舟车劳顿", "顿开茅塞", "塞翁失马", "马到成功", "功成名就",
            "就事论事", "事不过三", "三心二意", "意气风发", "发扬光大",
            "大公无私", "私心杂念", "念念不忘", "忘年之交", "交头接耳",
            "耳濡目染", "染指于鼎", "鼎鼎大名", "名不虚传", "传为美谈"
        ]
        return idioms
    
    def setup_ui(self):
        """设置主界面"""
        # 设置窗口背景
        self.root.configure(bg=self.colors['bg'])
        
        # 创建样式
        self.setup_styles()
        
    def setup_styles(self):
        """设置ttk样式"""
        style = ttk.Style()
        
        # 按钮样式
        style.configure('Cartoon.TButton',
                        font=self.button_font,
                        padding=10,
                        relief='raised',
                        background=self.colors['accent'],
                        foreground=self.colors['text'])
        
        style.map('Cartoon.TButton',
                 background=[('active', self.colors['warning'])])
        
        # 框架样式
        style.configure('Card.TFrame',
                       background=self.colors['frame'],
                       relief='solid',
                       borderwidth=2)
        
    def create_home_screen(self):
        """创建首页界面"""
        self.clear_window()
        
        # 主容器
        main_container = tk.Frame(self.root, bg=self.colors['bg'])
        main_container.pack(expand=True, fill='both', padx=20, pady=20)
        
        # 标题
        title_frame = tk.Frame(main_container, bg=self.colors['bg'])
        title_frame.pack(pady=(20, 10))
        
        emoji_label = tk.Label(title_frame, text="🎮✨🎯", font=("Arial", 40), 
                               bg=self.colors['bg'], fg=self.colors['primary'])
        emoji_label.pack()
        
        title_label = tk.Label(title_frame, text="卡通成语接龙大冒险", 
                              font=self.title_font, bg=self.colors['bg'], 
                              fg=self.colors['primary'])
        title_label.pack(pady=5)
        
        subtitle_label = tk.Label(title_frame, text="和可爱的伙伴们一起玩成语接龙吧！", 
                                 font=("Arial Rounded MT Bold", 14), 
                                 bg=self.colors['bg'], fg=self.colors['text'])
        subtitle_label.pack()
        
        # 游戏选项卡片
        options_frame = tk.Frame(main_container, bg=self.colors['bg'])
        options_frame.pack(pady=30)
        
        # 开始游戏按钮
        start_btn = self.create_cartoon_button(options_frame, "🎮 开始新游戏", 
                                               self.start_game, width=20)
        start_btn.pack(pady=10)
        
        # 选择角色按钮
        skin_btn = self.create_cartoon_button(options_frame, "🐱 选择角色", 
                                             self.select_skin, width=20)
        skin_btn.pack(pady=10)
        
        # 游戏规则按钮
        rules_btn = self.create_cartoon_button(options_frame, "📖 游戏规则", 
                                               self.show_rules, width=20)
        rules_btn.pack(pady=10)
        
        # 退出按钮
        quit_btn = self.create_cartoon_button(options_frame, "🚪 退出游戏", 
                                             self.root.quit, width=20)
        quit_btn.pack(pady=10)
        
        # 底部装饰
        bottom_frame = tk.Frame(main_container, bg=self.colors['bg'])
        bottom_frame.pack(side='bottom', pady=20)
        
        for _ in range(5):
            star = tk.Label(bottom_frame, text="⭐", font=("Arial", 16), 
                           bg=self.colors['bg'], fg=self.colors['accent'])
            star.pack(side='left', padx=5)
    
    def create_cartoon_button(self, parent, text, command, **kwargs):
        """创建卡通风格的按钮"""
        btn = tk.Button(parent, text=text, command=command,
                       font=self.button_font,
                       bg=self.colors['accent'],
                       fg=self.colors['text'],
                       activebackground=self.colors['warning'],
                       activeforeground='white',
                       relief='raised',
                       borderwidth=3,
                       cursor='hand2',
                       padx=20,
                       pady=10,
                       **kwargs)
        
        # 添加鼠标悬停效果
        btn.bind('<Enter>', lambda e: btn.configure(
            bg=self.colors['primary'],
            fg='white'
        ))
        btn.bind('<Leave>', lambda e: btn.configure(
            bg=self.colors['accent'],
            fg=self.colors['text']
        ))
        
        return btn
    
    def create_game_screen(self):
        """创建游戏界面"""
        self.clear_window()
        
        # 主容器
        main_container = tk.Frame(self.root, bg=self.colors['bg'])
        main_container.pack(expand=True, fill='both', padx=20, pady=20)
        
        # 顶部状态栏
        status_frame = self.create_card_frame(main_container)
        status_frame.pack(fill='x', pady=(0, 20))
        
        # 得分显示
        self.score_label = tk.Label(status_frame, 
                                   text=f"🏆 得分: {self.score}",
                                   font=self.heading_font,
                                   bg=self.colors['frame'],
                                   fg=self.colors['primary'])
        self.score_label.pack(side='left', padx=20, pady=10)
        
        # 连击显示
        self.combo_label = tk.Label(status_frame,
                                    text=f"🔥 连击: {self.combo} (最高: {self.max_combo})",
                                    font=self.normal_font,
                                    bg=self.colors['frame'],
                                    fg=self.colors['warning'])
        self.combo_label.pack(side='left', padx=20, pady=10)
        
        # 角色显示
        self.player_label = tk.Label(status_frame,
                                     text=f"{self.player_skin} 玩家",
                                     font=self.normal_font,
                                     bg=self.colors['frame'],
                                     fg=self.colors['player'])
        self.player_label.pack(side='right', padx=20, pady=10)
        
        # 游戏主区域
        game_area = tk.Frame(main_container, bg=self.colors['bg'])
        game_area.pack(expand=True, fill='both')
        
        # 左栏 - 当前成语显示
        left_frame = tk.Frame(game_area, bg=self.colors['bg'])
        left_frame.pack(side='left', fill='both', expand=True, padx=(0, 10))
        
        # 当前成语卡片
        current_frame = self.create_card_frame(left_frame, title="当前成语")
        current_frame.pack(fill='both', expand=True, pady=(0, 20))
        
        self.current_idiom_label = tk.Label(current_frame,
                                           text="点击开始游戏！",
                                           font=("Microsoft YaHei", 28, "bold"),
                                           bg='white',
                                           fg=self.colors['text'],
                                           relief='sunken',
                                           borderwidth=2,
                                           padx=30,
                                           pady=20)
        self.current_idiom_label.pack(pady=20, padx=20)
        
        # 接龙提示
        hint_frame = self.create_card_frame(left_frame, title="接龙提示")
        hint_frame.pack(fill='both', expand=True)
        
        self.hint_label = tk.Label(hint_frame,
                                  text="等待开始...",
                                  font=self.normal_font,
                                  bg=self.colors['frame'],
                                  fg=self.colors['text'])
        self.hint_label.pack(pady=20)
        
        # 右栏 - 输入和操作
        right_frame = tk.Frame(game_area, bg=self.colors['bg'])
        right_frame.pack(side='right', fill='both', expand=True, padx=(10, 0))
        
        # 输入区域
        input_frame = self.create_card_frame(right_frame, title="你的回合")
        input_frame.pack(fill='x', pady=(0, 20))
        
        tk.Label(input_frame, text="请输入4字成语:", 
                font=self.normal_font, bg=self.colors['frame']).pack(pady=(10, 5))
        
        self.idiom_var = tk.StringVar()
        self.idiom_entry = tk.Entry(input_frame,
                                   textvariable=self.idiom_var,
                                   font=self.idiom_font,
                                   justify='center',
                                   relief='groove',
                                   borderwidth=3)
        self.idiom_entry.pack(pady=10, padx=20, fill='x')
        self.idiom_entry.bind('<Return>', lambda e: self.submit_idiom())
        
        # 操作按钮
        button_frame = tk.Frame(input_frame, bg=self.colors['frame'])
        button_frame.pack(pady=20)
        
        self.create_cartoon_button(button_frame, "✅ 提交", 
                                  self.submit_idiom).pack(side='left', padx=5)
        self.create_cartoon_button(button_frame, "💡 提示", 
                                  self.get_hint).pack(side='left', padx=5)
        self.create_cartoon_button(button_frame, "🎲 随机", 
                                  self.get_random_hint).pack(side='left', padx=5)
        self.create_cartoon_button(button_frame, "⏭️ 跳过", 
                                  self.skip_turn).pack(side='left', padx=5)
        
        # 历史记录
        history_frame = self.create_card_frame(right_frame, title="接龙历史")
        history_frame.pack(fill='both', expand=True)
        
        # 创建文本框和滚动条
        text_frame = tk.Frame(history_frame, bg=self.colors['frame'])
        text_frame.pack(fill='both', expand=True, padx=10, pady=10)
        
        scrollbar = tk.Scrollbar(text_frame)
        scrollbar.pack(side='right', fill='y')
        
        self.history_text = tk.Text(text_frame,
                                   height=10,
                                   font=self.normal_font,
                                   bg='white',
                                   yscrollcommand=scrollbar.set,
                                   relief='sunken',
                                   borderwidth=2)
        self.history_text.pack(side='left', fill='both', expand=True)
        scrollbar.config(command=self.history_text.yview)
        
        # 控制按钮
        control_frame = tk.Frame(right_frame, bg=self.colors['bg'])
        control_frame.pack(fill='x', pady=(20, 0))
        
        self.create_cartoon_button(control_frame, "🏠 返回主页", 
                                  self.create_home_screen).pack(side='left', padx=5)
        self.create_cartoon_button(control_frame, "🔄 重新开始", 
                                  self.restart_game).pack(side='left', padx=5)
    
    def create_card_frame(self, parent, title=None):
        """创建卡片式框架"""
        frame = tk.Frame(parent, bg=self.colors['frame'], relief='solid', borderwidth=2)
        
        if title:
            title_frame = tk.Frame(frame, bg=self.colors['primary'])
            title_frame.pack(fill='x')
            
            tk.Label(title_frame, text=title, 
                    font=self.heading_font,
                    bg=self.colors['primary'],
                    fg='white',
                    padx=10,
                    pady=5).pack()
        
        return frame
    
    def select_skin(self):
        """选择角色皮肤"""
        skin_window = tk.Toplevel(self.root)
        skin_window.title("选择你的角色")
        skin_window.geometry("400x300")
        skin_window.configure(bg=self.colors['bg'])
        skin_window.transient(self.root)
        skin_window.grab_set()
        
        tk.Label(skin_window, text="请选择你的角色伙伴：", 
                font=self.heading_font, bg=self.colors['bg']).pack(pady=20)
        
        skin_frame = tk.Frame(skin_window, bg=self.colors['bg'])
        skin_frame.pack()
        
        for skin, name in self.skins.items():
            btn_frame = tk.Frame(skin_frame, bg=self.colors['bg'])
            btn_frame.pack(pady=5)
            
            btn = tk.Button(btn_frame, 
                          text=f"{skin} {name}",
                          command=lambda s=skin: self.set_skin(s, skin_window),
                          font=self.normal_font,
                          bg=self.colors['accent'],
                          relief='raised',
                          width=20)
            btn.pack()
            
            btn.bind('<Enter>', lambda e, b=btn: b.configure(bg=self.colors['primary'], fg='white'))
            btn.bind('<Leave>', lambda e, b=btn: b.configure(bg=self.colors['accent'], fg=self.colors['text']))
    
    def set_skin(self, skin, window):
        """设置角色皮肤"""
        self.player_skin = skin
        window.destroy()
        if hasattr(self, 'player_label'):
            self.player_label.config(text=f"{skin} 玩家")
        messagebox.showinfo("角色选择", f"你选择了{self.skins[skin]}！")
    
    def show_rules(self):
        """显示游戏规则"""
        rules = """
        🎮 卡通成语接龙游戏规则 🎮
        
        1. 📖 游戏目标：
           - 轮流接龙成语，每次说的成语必须以上一个成语的最后一个字开头
           - 尽量不让电脑接不上成语
        
        2. ⭐ 计分规则：
           - 成功接龙：+10分
           - 连续接龙（连击）：每次+5额外分
           - 使用提示：-5分
           - 跳过回合：-3分
        
        3. 🎯 游戏特色：
           - 多种可爱角色可选
           - 连击系统增加挑战性
           - 提示和随机功能帮助闯关
           - 卡通界面，乐趣十足
        
        4. ❌ 无效输入：
           - 成语不是4个字
           - 开头字不正确
           - 重复使用过的成语
           - 不是合法成语（可强制使用）
        
        祝您游戏愉快！🎉
        """
        messagebox.showinfo("游戏规则", rules)
    
    def start_game(self):
        """开始新游戏"""
        self.score = 0
        self.combo = 0
        self.max_combo = 0
        self.used_idioms.clear()
        self.game_active = True
        self.player_turn = True
        
        # 随机选择起始成语
        self.current_idiom = random.choice(self.idioms)
        self.used_idioms.add(self.current_idiom)
        
        # 切换到游戏界面
        self.create_game_screen()
        
        # 更新显示
        self.update_display()
        
        # 显示欢迎消息
        self.add_history(f"🎮 游戏开始！起始成语: {self.current_idiom}")
        self.add_history(f"👤 你的角色: {self.skins[self.player_skin]}")
        self.update_hint()
        
        # 聚焦到输入框
        self.idiom_entry.focus()
    
    def restart_game(self):
        """重新开始游戏"""
        response = messagebox.askyesno("重新开始", "确定要重新开始游戏吗？当前进度将丢失。")
        if response:
            self.start_game()
    
    def get_last_character(self, idiom):
        """获取成语的最后一个字（处理多音字）"""
        if not idiom:
            return ""
        
        last_char = idiom[-1]
        
        # 处理常见多音字映射
        polyphone_map = {
            '行': ['xing', 'hang'],  # 一行 xing -> 行业 hang
            '好': ['hao', 'hao'],     # 爱好 hao -> 好人 hao
            '长': ['zhang', 'chang'], # 成长 zhang -> 长短 chang
            '重': ['zhong', 'chong'], # 重量 zhong -> 重复 chong
        }
        
        return last_char
    
    def get_valid_idioms(self, start_char):
        """获取以指定字开头的可用成语"""
        valid = []
        for idiom in self.idioms:
            if idiom.startswith(start_char) and idiom not in self.used_idioms:
                valid.append(idiom)
        return valid
    
    def submit_idiom(self):
        """提交成语"""
        if not self.game_active:
            return
        
        user_input = self.idiom_var.get().strip()
        
        # 验证输入
        if not self.validate_input(user_input):
            return
        
        # 检查是否以最后一个字开头
        last_char = self.get_last_character(self.current_idiom)
        if not user_input.startswith(last_char):
            self.show_error(f"需要以『{last_char}』开头哦！")
            return
        
        # 检查是否重复
        if user_input in self.used_idioms:
            self.show_error("这个成语已经用过了，换一个吧！")
            return
        
        # 成功接龙
        self.process_successful_idiom(user_input)
    
    def validate_input(self, user_input):
        """验证用户输入"""
        if not user_input:
            self.show_error("请输入一个成语！")
            return False
        
        if len(user_input) != 4:
            self.show_error("成语必须是4个字哦！")
            return False
        
        return True
    
    def process_successful_idiom(self, idiom):
        """处理成功的接龙"""
        # 添加成语
        self.used_idioms.add(idiom)
        self.current_idiom = idiom
        
        # 更新分数
        self.score += 10
        self.combo += 1
        if self.combo > self.max_combo:
            self.max_combo = self.combo
        
        # 显示成功消息
        self.add_history(f"{self.player_skin} 玩家: {idiom} +10分", "player")
        self.update_display()
        
        # 清空输入框
        self.idiom_var.set("")
        
        # 检查游戏是否继续
        if not self.check_game_continue():
            return
        
        # 电脑回合
        self.root.after(1000, self.computer_turn)
    
    def computer_turn(self):
        """电脑回合"""
        if not self.game_active:
            return
        
        last_char = self.get_last_character(self.current_idiom)
        valid_idioms = self.get_valid_idioms(last_char)
        
        if valid_idioms:
            # 电脑"思考"一下
            self.add_history("🤔 电脑正在思考中...", "info")
            self.hint_label.config(text=f"{self.computer_skin} 正在思考...")
            self.root.update()
            
            # 延时模拟思考
            self.root.after(1500, lambda: self.computer_play(valid_idioms))
        else:
            self.game_over("玩家胜利！")
    
    def computer_play(self, valid_idioms):
        """电脑出题"""
        if not self.game_active:
            return
        
        # 电脑选择成语（有简单AI）
        computer_choice = self.choose_difficult_idiom(valid_idioms)
        self.used_idioms.add(computer_choice)
        self.current_idiom = computer_choice
        
        # 显示电脑的选择
        self.add_history(f"{self.computer_skin} 电脑: {computer_choice}", "computer")
        self.update_display()
        
        # 检查游戏是否继续
        self.check_game_continue()
    
    def choose_difficult_idiom(self, idioms):
        """选择较难的成语（增加游戏难度）"""
        # 优先选择结尾字不常见的成语
        difficult_scores = []
        for idiom in idioms:
            last_char = self.get_last_character(idiom)
            # 计算以这个字开头的成语数量
            count = sum(1 for i in self.idioms if i.startswith(last_char) and i not in self.used_idioms)
            score = 1.0 / (count + 1)  # 越少见得分越高
            difficult_scores.append((idiom, score))
        
        # 按难度排序
        difficult_scores.sort(key=lambda x: x[1], reverse=True)
        
        # 80%概率选择最难的，20%概率随机选择
        if random.random() < 0.8 and difficult_scores:
            return difficult_scores[0][0]
        else:
            return random.choice(idioms)
    
    def get_hint(self):
        """获取提示"""
        if not self.game_active:
            return
        
        if not self.current_idiom:
            self.show_error("请先开始游戏！")
            return
        
        # 扣分
        self.score = max(0, self.score - 5)
        
        last_char = self.get_last_character(self.current_idiom)
        valid_idioms = self.get_valid_idioms(last_char)
        
        if valid_idioms:
            hint = random.choice(valid_idioms)
            # 显示部分提示
            display_hint = hint[0] + "？" + hint[2] + "？"
            self.show_info(f"💡 提示: {display_hint}")
            self.add_history(f"💡 使用了提示 -5分", "hint")
            self.update_display()
        else:
            self.show_error("没有可用的提示了！")
    
    def get_random_hint(self):
        """获取随机提示（填到输入框）"""
        if not self.game_active:
            return
        
        if not self.current_idiom:
            self.show_error("请先开始游戏！")
            return
        
        last_char = self.get_last_character(self.current_idiom)
        valid_idioms = self.get_valid_idioms(last_char)
        
        if valid_idioms:
            random_idiom = random.choice(valid_idioms)
            self.idiom_var.set(random_idiom)
            self.add_history(f"🎲 获取了随机提示: {random_idiom}", "hint")
        else:
            self.show_error("没有可用的成语了！")
    
    def skip_turn(self):
        """跳过回合"""
        if not self.game_active:
            return
        
        # 扣分
        self.score = max(0, self.score - 3)
        self.combo = 0
        
        self.add_history(f"⏭️ 跳过了回合 -3分", "warning")
        self.update_display()
        
        # 电脑回合
        self.computer_turn()
    
    def check_game_continue(self):
        """检查游戏是否可以继续"""
        last_char = self.get_last_character(self.current_idiom)
        valid_idioms = self.get_valid_idioms(last_char)
        
        if not valid_idioms:
            self.game_over("游戏结束！没有可接龙的成语了。")
            return False
        
        return True
    
    def game_over(self, message):
        """游戏结束"""
        self.game_active = False
        
        # 显示结果
        result = f"""
        {message}
        
        🎮 游戏结果：
        🏆 最终得分: {self.score}
        🔥 最高连击: {self.max_combo}
        📊 使用成语: {len(self.used_idioms)}
        
        点击确定返回主菜单
        """
        
        self.add_history("=" * 30, "info")
        self.add_history(f"🎮 游戏结束！最终得分: {self.score}", "success")
        self.add_history(f"🏆 最高连击: {self.max_combo}", "success")
        
        messagebox.showinfo("游戏结束", result)
        self.create_home_screen()
    
    def update_display(self):
        """更新显示"""
        if hasattr(self, 'score_label'):
            self.score_label.config(text=f"🏆 得分: {self.score}")
            self.combo_label.config(text=f"🔥 连击: {self.combo} (最高: {self.max_combo})")
            
            if hasattr(self, 'current_idiom_label'):
                self.current_idiom_label.config(text=self.current_idiom)
            
            self.update_hint()
    
    def update_hint(self):
        """更新提示"""
        if not self.current_idiom:
            return
        
        last_char = self.get_last_character(self.current_idiom)
        valid_count = len(self.get_valid_idioms(last_char))
        
        if hasattr(self, 'hint_label'):
            self.hint_label.config(text=f"当前需要以『{last_char}』开头\n剩余可用成语: {valid_count}个")
    
    def add_history(self, message, msg_type="normal"):
        """添加历史记录"""
        if not hasattr(self, 'history_text'):
            return
        
        colors = {
            "player": self.colors['player'],
            "computer": self.colors['computer'],
            "success": self.colors['success'],
            "warning": self.colors['warning'],
            "hint": self.colors['secondary'],
            "info": self.colors['text'],
            "normal": "black"
        }
        
        color = colors.get(msg_type, "black")
        
        # 获取当前时间
        current_time = time.strftime("%H:%M:%S")
        
        # 插入带颜色的文本
        self.history_text.insert('end', f"[{current_time}] {message}\n")
        self.history_text.tag_add(msg_type, f"end-2l linestart", f"end-2l lineend")
        self.history_text.tag_config(msg_type, foreground=color)
        
        # 自动滚动到底部
        self.history_text.see('end')
    
    def show_error(self, message):
        """显示错误消息"""
        self.add_history(f"❌ {message}", "warning")
        self.idiom_var.set("")
        
        # 闪烁输入框
        for _ in range(3):
            self.idiom_entry.config(bg='red')
            self.root.update()
            time.sleep(0.1)
            self.idiom_entry.config(bg='white')
            self.root.update()
            time.sleep(0.1)
    
    def show_info(self, message):
        """显示信息消息"""
        messagebox.showinfo("提示", message)
    
    def clear_window(self):
        """清除窗口内容"""
        for widget in self.root.winfo_children():
            widget.destroy()

def main():
    """主函数"""
    root = tk.Tk()
    
    # 设置窗口图标和标题
    root.title("🎮 卡通成语接龙大冒险 🎮")
    root.geometry("900x700")
    
    # 创建游戏实例
    app = CartoonIdiomGame(root)
    
    # 运行主循环
    root.mainloop()

if __name__ == "__main__":
    main()
