import pygame
import random
import sys
import os
from pygame.locals import *

# 初始化pygame
pygame.init()

# 游戏窗口设置
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("成语接龙")

# 颜色定义
BACKGROUND = (240, 245, 240)  # 浅绿色背景
TEXT_COLOR = (30, 30, 30)     # 深灰色文字
HIGHLIGHT = (220, 60, 60)     # 红色高亮
BUTTON_COLOR = (80, 160, 80)  # 绿色按钮
BUTTON_HOVER = (100, 180, 100)
PLAYER_COLOR = (70, 130, 180)  # 玩家颜色
AI_COLOR = (180, 70, 130)      # AI颜色

# 尝试加载中文字体


def load_font(size):
    """尝试加载多种中文字体"""
    # 常见的中文字体文件名列表
    font_files = [
        "simhei.ttf",  # 黑体
        "simkai.ttf",  # 楷体
        "simsun.ttc",  # 宋体
        "msyh.ttc",    # 微软雅黑
        "msyhbd.ttc",  # 微软雅黑粗体
        "STZHONGS.ttf",  # 华文中宋
        "Deng.ttf",     # 等线
    ]

    # 尝试当前目录
    font_paths = [""]

    # 根据操作系统添加系统字体路径
    if sys.platform.startswith('win'):
        font_paths.append("C:/Windows/Fonts/")
    elif sys.platform.startswith('darwin'):
        font_paths.append("/System/Library/Fonts/")
        font_paths.append("/Library/Fonts/")
    else:  # Linux/Unix
        font_paths.append("/usr/share/fonts/")

    # 尝试加载字体
    for font_file in font_files:
        for font_path in font_paths:
            try:
                full_path = os.path.join(font_path, font_file)
                if os.path.exists(full_path):
                    return pygame.font.Font(full_path, size)
            except:
                continue

    # 如果都找不到，使用系统默认字体
    print("提示: 使用系统默认字体，中文可能显示不清晰")
    print("建议: 将中文字体文件(如simhei.ttf)放在游戏目录下")
    return pygame.font.Font(None, size)


# 加载字体
font_large = load_font(48)
font_medium = load_font(36)
font_small = load_font(28)

# 加载成语库
idioms = [
    "一帆风顺", "二龙戏珠", "三心二意", "四面楚歌", "五光十色",
    "六神无主", "七上八下", "八仙过海", "九牛一毛", "十全十美",
    "人山人海", "天衣无缝", "地久天长", "春暖花开", "秋高气爽",
    "心想事成", "马到成功", "画龙点睛", "一鸣惊人", "龙飞凤舞",
    "风雨同舟", "海阔天空", "一见钟情", "百花齐放", "千军万马",
    "万众一心", "一马当先", "三思而行", "四海为家", "五彩缤纷",
    "六六大顺", "七手八脚", "八面玲珑", "九九归一", "十万火急"
]

# 创建按首字母分类的成语字典
idiom_dict = {}
for idiom in idioms:
    first_char = idiom[0]
    if first_char not in idiom_dict:
        idiom_dict[first_char] = []
    idiom_dict[first_char].append(idiom)


class Button:
    def __init__(self, x, y, width, height, text, action=None):
        self.rect = pygame.Rect(x, y, width, height)
        self.text = text
        self.action = action
        self.is_hovered = False

    def draw(self, surface):
        color = BUTTON_HOVER if self.is_hovered else BUTTON_COLOR
        pygame.draw.rect(surface, color, self.rect, border_radius=10)
        pygame.draw.rect(surface, (50, 50, 50), self.rect, 3, border_radius=10)

        # 渲染文本
        try:
            text_surf = font_medium.render(self.text, True, (255, 255, 255))
        except:
            text_surf = font_medium.render(self.text.encode(
                'utf-8').decode('utf-8'), True, (255, 255, 255))

        text_rect = text_surf.get_rect(center=self.rect.center)
        surface.blit(text_surf, text_rect)

    def check_hover(self, pos):
        self.is_hovered = self.rect.collidepoint(pos)

    def handle_event(self, event):
        if event.type == MOUSEBUTTONDOWN and event.button == 1:
            if self.rect.collidepoint(event.pos) and self.action:
                return self.action()
        return None


class Game:
    def __init__(self):
        self.current_idiom = ""
        self.history = []  # 存储(玩家/ai, 成语)
        self.game_over = False
        self.winner = None
        self.message = ""
        self.input_text = ""
        self.available_idioms = []

        # 创建按钮
        button_width, button_height = 150, 50
        center_x = WIDTH // 2 - button_width // 2
        self.submit_button = Button(
            center_x, 500, button_width, button_height, "提交", self.submit_idiom)
        self.restart_button = Button(
            center_x, 500, button_width, button_height, "重新开始", self.restart_game)
        self.hint_button = Button(
            center_x + 200, 500, 100, 50, "提示", self.show_hint)

        # 开始游戏
        self.message = "游戏开始！请输入一个成语"

    def get_last_char(self):
        """获取当前接龙的最后一个字"""
        if not self.current_idiom:
            return ""
        return self.current_idiom[-1]

    def update_available_idioms(self):
        """更新可用的成语列表"""
        last_char = self.get_last_char()
        if last_char and last_char in idiom_dict:
            # 过滤掉已经使用过的成语
            used_idioms = [idiom for _, idiom in self.history]
            self.available_idioms = [
                idiom for idiom in idiom_dict[last_char]
                if idiom not in used_idioms
            ]
        else:
            self.available_idioms = []

    def is_valid_idiom(self, idiom, is_ai=False):
        """检查成语是否有效"""
        if idiom not in idioms:
            return False, "这不是一个有效成语！"

        if idiom in [h[1] for h in self.history]:
            return False, "这个成语已经用过了！"

        if self.current_idiom:  # 不是第一个成语
            last_char = self.get_last_char()
            if idiom[0] != last_char:
                return False, f"需要以'{last_char}'开头！"

        return True, ""

    def ai_turn(self):
        """AI回合"""
        last_char = self.get_last_char()

        if not last_char or last_char not in idiom_dict:
            self.game_over = True
            self.winner = "玩家"
            self.message = f"AI接不上'{last_char}'开头的成语，玩家获胜！"
            return

        # 从可用成语中随机选择一个
        available = [idiom for idiom in idiom_dict[last_char]
                     if idiom not in [h[1] for h in self.history]]

        if not available:
            self.game_over = True
            self.winner = "玩家"
            self.message = f"AI接不上'{last_char}'开头的成语，玩家获胜！"
            return

        ai_choice = random.choice(available)
        self.history.append(("AI", ai_choice))
        self.current_idiom = ai_choice
        self.message = f"AI接龙: {ai_choice}"

        # 检查玩家是否能接上AI的成语
        self.update_available_idioms()
        if not self.available_idioms and len(self.history) < len(idioms):
            self.game_over = True
            self.winner = "AI"
            self.message = f"AI出的成语'{ai_choice}'是死胡同，AI获胜！"

    def submit_idiom(self):
        """玩家提交成语"""
        if not self.input_text or self.game_over:
            return

        idiom = self.input_text.strip()
        is_valid, error_msg = self.is_valid_idiom(idiom)

        if not is_valid:
            self.message = error_msg
            return

        # 添加玩家成语到历史
        self.history.append(("玩家", idiom))
        self.current_idiom = idiom
        self.message = f"你输入: {idiom}"
        self.input_text = ""

        # 检查游戏是否结束
        if len(self.history) >= len(idioms):
            self.game_over = True
            self.winner = "平局"
            self.message = "所有成语已用完，游戏结束！"
            return

        # AI回合
        self.ai_turn()

    def show_hint(self):
        """显示提示"""
        if not self.game_over:
            self.update_available_idioms()
            if self.available_idioms:
                hint = random.choice(self.available_idioms[:3])  # 从前3个中选
                self.message = f"提示: 可以接 '{hint}'"
            else:
                self.message = "提示: 暂时没有可用成语"

    def restart_game(self):
        """重新开始游戏"""
        self.__init__()
        return True

    def draw(self, surface):
        """绘制游戏界面"""
        surface.fill(BACKGROUND)

        # 绘制标题
        try:
            title = font_large.render("成语接龙", True, (30, 100, 30))
        except:
            title = font_large.render("成语接龙", True, (30, 100, 30))

        surface.blit(title, (WIDTH//2 - title.get_width()//2, 30))

        # 绘制当前状态
        status_y = 100
        if self.current_idiom:
            last_char = self.get_last_char()
            status_text = f"当前接龙: {self.current_idiom} → 需要以'{last_char}'开头"
            try:
                status = font_medium.render(status_text, True, HIGHLIGHT)
            except:
                status = font_medium.render(status_text, True, HIGHLIGHT)
            surface.blit(status, (WIDTH//2 - status.get_width()//2, status_y))

        # 绘制输入框
        input_y = 150
        pygame.draw.rect(surface, (255, 255, 255),
                         (200, input_y, 400, 50), border_radius=8)
        pygame.draw.rect(surface, (100, 100, 100),
                         (200, input_y, 400, 50), 3, border_radius=8)

        # 绘制输入文本
        input_text = self.input_text if self.input_text else "点击此处输入成语"
        input_color = TEXT_COLOR if self.input_text else (150, 150, 150)
        try:
            input_surf = font_medium.render(input_text, True, input_color)
        except:
            input_surf = font_medium.render(input_text, True, input_color)
        surface.blit(input_surf, (210, input_y + 10))

        # 绘制历史记录
        history_y = 220
        try:
            history_title = font_medium.render("接龙历史:", True, TEXT_COLOR)
        except:
            history_title = font_medium.render("接龙历史:", True, TEXT_COLOR)
        surface.blit(history_title, (50, history_y))

        for i, (player, idiom) in enumerate(self.history[-8:]):  # 显示最后8条记录
            player_color = PLAYER_COLOR if player == "玩家" else AI_COLOR
            text = f"{player}: {idiom}"
            try:
                history_item = font_small.render(text, True, player_color)
            except:
                history_item = font_small.render(text, True, player_color)
            surface.blit(history_item, (50, history_y + 40 + i * 30))

        # 绘制消息
        message_y = 500 if not self.game_over else 450
        message_color = HIGHLIGHT if "获胜" in self.message or "结束" in self.message else TEXT_COLOR

        try:
            message_surf = font_medium.render(
                self.message, True, message_color)
        except:
            message_surf = font_medium.render(
                self.message, True, message_color)

        surface.blit(message_surf, (WIDTH//2 -
                     message_surf.get_width()//2, message_y))

        # 绘制按钮
        if not self.game_over:
            self.submit_button.draw(surface)
            self.hint_button.draw(surface)
        else:
            self.restart_button.draw(surface)

        # 绘制游戏规则
        rules = [
            "游戏规则:",
            "1. 玩家和AI轮流接龙成语",
            "2. 每个成语的首字必须与上一个成语的尾字相同",
            "3. 不能重复使用已出现的成语",
            "4. 接不上的一方判负"
        ]

        for i, rule in enumerate(rules):
            try:
                rule_surf = font_small.render(rule, True, (100, 100, 100))
            except:
                rule_surf = font_small.render(rule, True, (100, 100, 100))
            surface.blit(rule_surf, (WIDTH - 350, 100 + i * 30))

    def handle_event(self, event):
        """处理事件"""
        if not self.game_over:
            result = self.submit_button.handle_event(event)
            if result is not None:
                return

            result = self.hint_button.handle_event(event)
            if result is not None:
                return
        else:
            result = self.restart_button.handle_event(event)
            if result is not None:
                return

        if event.type == KEYDOWN and not self.game_over:
            if event.key == K_RETURN:  # 回车提交
                self.submit_idiom()
            elif event.key == K_BACKSPACE:  # 退格删除
                self.input_text = self.input_text[:-1]
            elif event.key == K_ESCAPE:  # ESC退出
                pygame.quit()
                sys.exit()
            elif event.unicode and len(self.input_text) < 10:  # 限制输入长度
                # 只接受中文字符
                if '\u4e00' <= event.unicode <= '\u9fff':
                    self.input_text += event.unicode
            elif event.key == K_SPACE:  # 空格键清空输入
                self.input_text = ""

        # 点击输入框开始输入
        if event.type == MOUSEBUTTONDOWN and event.button == 1:
            input_rect = pygame.Rect(200, 150, 400, 50)
            if input_rect.collidepoint(event.pos) and not self.game_over:
                pygame.key.set_repeat(500, 50)  # 启用键盘重复


def main():
    clock = pygame.time.Clock()
    game = Game()

    # 显示字体加载提示
    print("成语接龙游戏启动...")
    print("操作说明:")
    print("1. 输入成语后按回车提交")
    print("2. 点击提示按钮获取建议")
    print("3. 按ESC键退出游戏")

    running = True
    while running:
        mouse_pos = pygame.mouse.get_pos()

        for event in pygame.event.get():
            if event.type == QUIT:
                running = False
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                running = False
            else:
                game.handle_event(event)

        # 更新按钮悬停状态
        if not game.game_over:
            game.submit_button.check_hover(mouse_pos)
            game.hint_button.check_hover(mouse_pos)
        else:
            game.restart_button.check_hover(mouse_pos)

        # 绘制游戏
        game.draw(screen)
        pygame.display.flip()
        clock.tick(60)

    pygame.quit()
    sys.exit()


if __name__ == "__main__":
    main()
