import json
import random
from typing import Dict, List

class IdiomSolitaire:
    def __init__(self):
        # 初始化成语库：格式 {成语: 拼音}
        self.idiom_database = self._load_idioms()
        # 同音字映射表（解决发音相同字形不同的问题）
        self.homophones = {
            "yi": ["一", "以", "依", "伊", "衣"],
            "er": ["二", "儿", "耳"],
            "san": ["三", "叁"],
            "si": ["四", "似", "寺"],
            "wu": ["五", "无", "吾"],
            "liu": ["六", "流", "留"],
            "qi": ["七", "期", "其"],
            "ba": ["八", "巴", "吧"],
            "jiu": ["九", "久", "酒"],
            "shi": ["十", "时", "石", "食"],
            # 可根据需要扩展更多同音字
        }
        # 游戏状态
        self.used_idioms = set()  # 记录已使用的成语
        self.current_char = ""    # 当前需要接的字
        self.user_score = 0       # 用户得分
        self.computer_score = 0   # 电脑得分

    def _load_idioms(self) -> Dict[str, str]:
        """加载成语库"""
        # 内置常用成语库
        idioms = {
            "一帆风顺": "yī fān fēng shùn",
            "二龙戏珠": "èr lóng xì zhū",
            "三顾茅庐": "sān gù máo lú",
            "四通八达": "sì tōng bā dá",
            "五光十色": "wǔ guāng shí sè",
            "六神无主": "liù shén wú zhǔ",
            "七上八下": "qī shàng bā xià",
            "八面玲珑": "bā miàn líng lóng",
            "九牛一毛": "jiǔ niú yī máo",
            "十全十美": "shí quán shí měi",
            "百发百中": "bǎi fā bǎi zhòng",
            "千军万马": "qiān jūn wàn mǎ",
            "万紫千红": "wàn zǐ qiān hóng",
            "龙马精神": "lóng mǎ jīng shén",
            "神出鬼没": "shén chū guǐ mò",
            "没齿难忘": "mò chǐ nán wàng",
            "忘乎所以": "wàng hū suǒ yǐ",
            "以逸待劳": "yǐ yì dài láo",
            "劳燕分飞": "láo yàn fēn fēi",
            "飞檐走壁": "fēi yán zǒu bì"
        }
        return idioms

    def _get_last_pinyin(self, idiom: str) -> str:
        """获取成语最后一个字的拼音（不带声调）"""
        if idiom not in self.idiom_database:
            return ""
        pinyin = self.idiom_database[idiom]
        # 移除声调数字
        pinyin_without_tone = ''.join([c for c in pinyin if not c.isdigit()])
        # 返回最后一个音节
        return pinyin_without_tone.split()[-1]

    def _get_first_pinyin(self, idiom: str) -> str:
        """获取成语第一个字的拼音（不带声调）"""
        if idiom not in self.idiom_database:
            return ""
        pinyin = self.idiom_database[idiom]
        pinyin_without_tone = ''.join([c for c in pinyin if not c.isdigit()])
        return pinyin_without_tone.split()[0]

    def _find_matching_idiom(self, target_pinyin: str) -> str:
        """根据拼音查找可以接龙的成语"""
        candidates = []
        for idiom in self.idiom_database:
            if idiom not in self.used_idioms:
                first_pinyin = self._get_first_pinyin(idiom)
                if first_pinyin == target_pinyin:
                    candidates.append(idiom)
        
        if candidates:
            return random.choice(candidates)
        return ""

    def _is_valid_idiom(self, idiom: str) -> bool:
        """验证成语是否有效"""
        # 检查是否在成语库中
        if idiom not in self.idiom_database:
            return False
        # 检查是否已经使用过
        if idiom in self.used_idioms:
            return False
        # 检查接龙规则
        if self.current_char:
            target_pinyin = self._get_last_pinyin(self.current_char)
            user_pinyin = self._get_first_pinyin(idiom)
            if user_pinyin != target_pinyin:
                return False
        return True

    def start_game(self):
        """开始游戏"""
        print("=" * 50)
        print("        欢迎使用成语接龙游戏        ")
        print("=" * 50)
        print("游戏规则：")
        print("1. 输入成语进行接龙，最后一个字接第一个字（支持同音字）")
        print("2. 不能重复使用成语")
        print("3. 输入 '退出' 可结束游戏")
        print("4. 输入 '开始' 开始游戏")
        print("=" * 50)

        # 等待用户开始
        while True:
            user_input = input("请输入指令（开始/退出）：")
            if user_input == "退出":
                print("游戏已退出")
                return
            elif user_input == "开始":
                break
            else:
                print("无效指令，请重新输入！")

        # 随机选择第一个成语（电脑先手）
        first_idiom = random.choice(list(self.idiom_database.keys()))
        self.current_char = first_idiom
        self.used_idioms.add(first_idiom)
        print(f"\n电脑先出：{first_idiom}")
        print(f"请用 '{first_idiom[-1]}' 开头（同音）的成语接龙...\n")

        # 游戏主循环
        while True:
            # 用户回合
            user_idiom = input("请输入你的成语：")
            
            # 退出游戏
            if user_idiom == "退出":
                break
            
            # 验证用户输入
            if not self._is_valid_idiom(user_idiom):
                print(f"❌ 成语 '{user_idiom}' 无效！可能原因：")
                print("  1. 不在成语库中")
                print("  2. 已经使用过")
                print("  3. 不符合接龙规则")
                continue
            
            # 用户接龙成功
            self.used_idioms.add(user_idiom)
            self.user_score += 1
            print(f"✅ 接龙成功！当前得分：你 {self.user_score} - {self.computer_score} 电脑")
            
            # 电脑回合
            target_pinyin = self._get_last_pinyin(user_idiom)
            computer_idiom = self._find_matching_idiom(target_pinyin)
            
            if not computer_idiom:
                print("\n🎉 电脑接不上了！你赢了！")
                break
            
            self.used_idioms.add(computer_idiom)
            self.computer_score += 1
            self.current_char = computer_idiom
            print(f"💻 电脑接龙：{computer_idiom}")
            print(f"请用 '{computer_idiom[-1]}' 开头（同音）的成语接龙...")
            print(f"当前得分：你 {self.user_score} - {self.computer_score} 电脑\n")

        # 游戏结束
        print("\n" + "=" * 50)
        print("游戏结束！")
        print(f"最终得分：你 {self.user_score} - {self.computer_score} 电脑")
        if self.user_score > self.computer_score:
            print("🏆 恭喜你获得胜利！")
        elif self.user_score < self.computer_score:
            print("😥 电脑获得胜利，继续加油！")
        else:
            print("🤝 平局！")
        print(f"总共使用了 {len(self.used_idioms)} 个成语")
        print("使用过的成语：", " | ".join(self.used_idioms))
        print("=" * 50)

if __name__ == "__main__":
    # 创建游戏实例并启动
    game = IdiomSolitaire()
    game.start_game()