import random
import os

def load_idioms(file_path="idiom.txt"):
    """加载外部txt成语库，自动去空白、去重复"""
    idiom_list = []
    if not os.path.exists(file_path):
        print(f"警告：未找到 {file_path}，使用内置备用成语库！")
        return [
            "一帆风顺", "两全其美", "三心二意", "四面八方", "五光十色",
            "六神无主", "七上八下", "八面玲珑", "九牛一毛", "十全十美",
            "美中不足", "足智多谋", "谋事在人", "人定胜天", "天罗地网"
        ]
    with open(file_path, "r", encoding="utf-8") as f:
        for line in f:
            word = line.strip()
            if len(word) >= 4:
                idiom_list.append(word)
    # 去重
    idiom_list = list(set(idiom_list))
    return idiom_list

def clean_input(text):
    """输入容错：清除所有空格"""
    return text.replace(" ", "").strip()

def get_next_idiom(last_char, used_idioms, all_idioms, difficulty):
    """
    根据难度寻找可接成语
    difficulty: 1简单 2普通 3困难
    """
    candidates = [w for w in all_idioms if w[0] == last_char and w not in used_idioms]
    if not candidates:
        return None

    if difficulty == 1:
        # 简单：优先靠前、容易接续，随机浅度筛选
        random.shuffle(candidates)
        return candidates[0]
    elif difficulty == 2:
        # 普通完全随机
        return random.choice(candidates)
    else:
        # 困难：优先选择尾部汉字匹配少的成语，提高难度
        candidates.sort(key=lambda x: len([w for w in all_idioms if w[0] == x[-1]]))
        return candidates[0]

def main():
    all_idioms = load_idioms()
    idiom_set = set(all_idioms)
    print("=" * 40)
    print("          🎮 成语接龙游戏")
    print("=" * 40)
    print("难度选择：")
    print("【1】简单 【2】普通 【3】困难")

    # 选择难度
    while True:
        diff_input = input("请输入难度数字(1/2/3)：").strip()
        if diff_input in ["1", "2", "3"]:
            difficulty = int(diff_input)
            break
        print("输入错误，请输入 1、2 或 3！")

    print("\n【游戏说明】")
    print("1. 输入成语接龙，尾字对接下一成语首字")
    print("2. 一局内成语不能重复使用")
    print("3. 输入 q 随时退出游戏\n")

    used_idioms = set()
    player_score = 0
    computer_score = 0
    round_count = 0

    # 获取开局成语
    while True:
        raw = input("请输入第一个成语：")
        player_word = clean_input(raw)
        if player_word.lower() == "q":
            print("游戏退出！")
            return
        if player_word not in idiom_set:
            print("⚠ 不是有效成语，请重新输入！")
            continue
        used_idioms.add(player_word)
        current_word = player_word
        print(f"👤 你：{current_word}")
        break

    # 主游戏循环
    while True:
        round_count += 1
        target_start_char = current_word[-1]
        comp_word = get_next_idiom(target_start_char, used_idioms, all_idioms, difficulty)

        if comp_word is None:
            print(f"\n🎉 电脑找不到以【{target_start_char}】开头的成语！你获胜！")
            player_score += 1
            break

        print(f"🤖 电脑：{comp_word}")
        used_idioms.add(comp_word)
        current_word = comp_word
        need_char = current_word[-1]

        # 玩家输入回合
        while True:
            raw_input_text = input(f"\n轮到你，请以【{need_char}】开头接龙：")
            player_next = clean_input(raw_input_text)
            if player_next.lower() == "q":
                print("\n===== 游戏结算 =====")
                print(f"总回合数：{round_count}")
                print(f"你的得分：{player_score}")
                print(f"电脑得分：{computer_score}")
                print("游戏结束！")
                return

            if player_next not in idiom_set:
                print("⚠ 该词语不是成语，重新输入！")
                continue
            if player_next in used_idioms:
                print("⚠ 这个成语本局已经用过了，不能重复！")
                continue
            if player_next[0] != need_char:
                print(f"⚠ 必须以【{need_char}】开头，不符合接龙规则！")
                continue

            # 玩家接龙成功
            print(f"👤 你：{player_next}")
            used_idioms.add(player_next)
            current_word = player_next
            break

    # 最终结算
    print("\n===== 📊 本局战绩 =====")
    print(f"进行回合：{round_count}")
    print(f"玩家分数：{player_score}")
    print(f"电脑分数：{computer_score}")

if __name__ == "__main__":
    main()