import pygame
import sys
import random
import time

# 初始化pygame
pygame.init()

# 游戏窗口设置
SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 700
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("成语接龙大挑战 - 汉字版")
clock = pygame.time.Clock()
FPS = 60

# 颜色定义
BACKGROUND_COLOR = (20, 30, 50)
TEXT_WHITE = (255, 255, 255)
TEXT_GOLD = (255, 215, 0)
TEXT_BLUE = (100, 200, 255)
TEXT_GREEN = (100, 255, 100)
TEXT_RED = (255, 100, 100)
TEXT_PURPLE = (200, 100, 255)
BUTTON_COLOR = (50, 150, 255)
BUTTON_HOVER = (100, 200, 255)
BUTTON_DISABLED = (100, 100, 150)
INPUT_BG_COLOR = (40, 60, 80)
INPUT_BORDER_COLOR = (100, 200, 255)
PLAYER_1_COLOR = (100, 200, 255)
PLAYER_2_COLOR = (255, 150, 100)
AI_COLOR = (150, 255, 150)
HISTORY_BG_COLOR = (30, 40, 60, 200)

# 直接使用系统字体，避免字体加载问题
try:
    font_small = pygame.font.Font(None, 24)
    font_medium = pygame.font.Font(None, 36)
    font_large = pygame.font.Font(None, 48)
    font_huge = pygame.font.Font(None, 64)
except:
    font_small = pygame.font.SysFont(None, 24)
    font_medium = pygame.font.SysFont(None, 36)
    font_large = pygame.font.SysFont(None, 48)
    font_huge = pygame.font.SysFont(None, 64)

# 成语数据库 - 直接在代码中提供
idioms = [
    "一心一意", "三心二意", "四面八方", "五光十色", "六神无主", 
    "七上八下", "八仙过海", "九牛一毛", "十全十美", "百家争鸣",
    "千军万马", "万紫千红", "一马当先", "二龙戏珠", "三阳开泰",
    "四海为家", "五湖四海", "六六大顺", "七步成诗", "八面玲珑",
    "九死一生", "十年树木", "百花齐放", "千钧一发", "万众一心",
    "一见钟情", "二话不说", "三思而行", "四海升平", "五谷丰登",
    "六根清净", "七嘴八舌", "八面威风", "九九归一", "十拿九稳",
    "百发百中", "千变万化", "万无一失", "一鸣惊人", "二分明月",
    "三顾茅庐", "四通八达", "五颜六色", "六亲不认", "七窍生烟",
    "八拜之交", "九霄云外", "十室九空", "百折不挠", "千山万水",
    "万里长征", "一箭双雕", "二人同心", "三生有幸", "四平八稳",
    "五体投地", "六畜兴旺", "七零八落", "八斗之才", "九泉之下",
    "十万火急", "百无禁忌", "千载难逢", "万水千山", "一鼓作气",
    "二八年华", "三长两短", "四分五裂", "十字路口", "百战百胜",
    "千方百计", "万念俱灰", "一往无前", "二三其德", "三皇五帝",
    "四大皆空", "五彩缤纷", "六朝金粉", "七情六欲", "八方呼应",
    "九流十家", "百尺竿头", "千篇一律", "万马奔腾", "一丝不苟",
    "二满三平", "三头六臂", "四时八节", "五谷不分", "七拼八凑",
    "八百孤寒", "九牛二虎", "十指连心", "百里挑一", "千呼万唤",
    "万古长青", "一视同仁", "二八佳人", "三教九流", "四书五经",
    "五脏六腑", "七老八十", "八荒之外", "九死未悔", "十年寒窗",
    "百代文宗", "千里迢迢", "万死不辞", "一败涂地", "二竖为虐",
    "三位一体", "四面楚歌", "五味俱全", "六尺之孤", "七颠八倒",
    "八面见光", "九九艳阳", "百花争艳", "千秋万代", "万古流芳"
]

# 输入框类
class InputBox:
    def __init__(self, x, y, width, height, text=''):
        self.rect = pygame.Rect(x, y, width, height)
        self.color = INPUT_BORDER_COLOR
        self.text = text
        self.font = font_large
        self.active = False
        self.cursor_visible = True
        self.cursor_timer = 0
        
    def handle_event(self, event):
        if event.type == pygame.MOUSEBUTTONDOWN:
            self.active = self.rect.collidepoint(event.pos)
            self.color = TEXT_BLUE if self.active else INPUT_BORDER_COLOR
            
        if event.type == pygame.KEYDOWN and self.active:
            if event.key == pygame.K_RETURN or event.key == pygame.K_KP_ENTER:
                return self.text
            elif event.key == pygame.K_BACKSPACE:
                self.text = self.text[:-1]
            elif event.key == pygame.K_ESCAPE:
                self.text = ''
            else:
                if len(self.text) < 4 and event.unicode.isprintable():
                    self.text += event.unicode
        return None
        
    def update(self):
        self.cursor_timer += 1
        if self.cursor_timer >= 30:
            self.cursor_visible = not self.cursor_visible
            self.cursor_timer = 0
            
    def draw(self, surface):
        # 绘制背景
        pygame.draw.rect(surface, INPUT_BG_COLOR, self.rect, border_radius=10)
        pygame.draw.rect(surface, self.color, self.rect, 3, border_radius=10)
        
        # 绘制文字
        if self.text:
            try:
                text_surface = self.font.render(self.text, True, TEXT_WHITE)
                text_x = self.rect.x + 20
                text_y = self.rect.y + (self.rect.height - text_surface.get_height()) // 2
                surface.blit(text_surface, (text_x, text_y))
            except:
                # 如果渲染失败，尝试用简单的方法显示
                pass
        
        # 绘制占位符
        if not self.text and not self.active:
            try:
                placeholder = font_medium.render("输入四字成语", True, (150, 150, 150))
                placeholder_x = self.rect.x + 20
                placeholder_y = self.rect.y + (self.rect.height - placeholder.get_height()) // 2
                surface.blit(placeholder, (placeholder_x, placeholder_y))
            except:
                pass
            
        # 绘制光标
        if self.active and self.cursor_visible:
            cursor_x = self.rect.x + 20
            if self.text:
                try:
                    cursor_x += self.font.render(self.text, True, TEXT_WHITE).get_width()
                except:
                    cursor_x += len(self.text) * 20
            pygame.draw.line(surface, TEXT_WHITE, 
                           (cursor_x, self.rect.y + 10),
                           (cursor_x, self.rect.y + self.rect.height - 10), 3)

# 按钮类
class Button:
    def __init__(self, x, y, width, height, text, action=None, color=BUTTON_COLOR):
        self.rect = pygame.Rect(x, y, width, height)
        self.text = text
        self.action = action
        self.color = color
        self.hover_color = BUTTON_HOVER
        self.current_color = color
        self.hover = False
        
    def draw(self, surface):
        color = self.hover_color if self.hover else self.color
        
        # 绘制按钮
        pygame.draw.rect(surface, color, self.rect, border_radius=10)
        pygame.draw.rect(surface, TEXT_WHITE, self.rect, 2, border_radius=10)
        
        # 绘制文字
        try:
            text_surf = font_medium.render(self.text, True, TEXT_WHITE)
            text_rect = text_surf.get_rect(center=self.rect.center)
            surface.blit(text_surf, text_rect)
        except:
            # 如果渲染失败，用简单的方法
            pass
        
    def check_hover(self, pos):
        self.hover = self.rect.collidepoint(pos)
        return self.hover
    
    def check_click(self, pos):
        if self.rect.collidepoint(pos) and self.action:
            return self.action
        return None

# 游戏主类
class IdiomGame:
    def __init__(self):
        self.state = "menu"  # menu, playing, game_over
        self.game_mode = "single"  # single, two_player, ai
        self.current_player = 1
        self.last_idiom = ""
        self.used_idioms = []
        self.input_box = InputBox(350, 450, 300, 60)
        self.buttons = []
        self.score_player1 = 0
        self.score_player2 = 0
        self.timer = 30
        self.last_time = time.time()
        self.game_start_time = 0
        self.message = ""
        self.message_time = 0
        self.init_menu()
        
    def init_menu(self):
        """初始化菜单"""
        button_width, button_height = 300, 70
        center_x = SCREEN_WIDTH // 2
        
        self.buttons = [
            Button(center_x - button_width//2, 300, button_width, button_height, 
                  "单人游戏", lambda: self.start_game("single")),
            Button(center_x - button_width//2, 390, button_width, button_height, 
                  "双人对战", lambda: self.start_game("two_player")),
            Button(center_x - button_width//2, 480, button_width, button_height, 
                  "人机对战", lambda: self.start_game("ai")),
            Button(center_x - button_width//2, 570, button_width, button_height, 
                  "退出游戏", self.quit_game)
        ]
        
    def start_game(self, mode):
        """开始游戏"""
        self.state = "playing"
        self.game_mode = mode
        self.current_player = 1
        self.last_idiom = ""
        self.used_idioms = []
        self.score_player1 = 0
        self.score_player2 = 0
        self.timer = 30
        self.last_time = time.time()
        self.game_start_time = time.time()
        self.message = ""
        self.input_box.text = ""
        self.input_box.active = True
        
        # 设置初始成语
        self.last_idiom = random.choice(idioms)
        self.used_idioms.append(self.last_idiom)
        
    def quit_game(self):
        """退出游戏"""
        pygame.quit()
        sys.exit()
        
    def show_message(self, message):
        """显示消息"""
        self.message = message
        self.message_time = time.time()
        
    def submit_idiom(self, idiom):
        """提交成语"""
        idiom = idiom.strip()
        
        if not idiom:
            self.show_message("请输入成语！")
            return False
            
        if len(idiom) != 4:
            self.show_message("成语必须是4个字！")
            return False
            
        if idiom not in idioms:
            self.show_message("这不是一个有效的成语！")
            return False
            
        if self.last_idiom and idiom[0] != self.last_idiom[-1]:
            self.show_message(f"请以'{self.last_idiom[-1]}'开头！")
            return False
            
        if idiom in self.used_idioms:
            self.show_message("这个成语已经用过了！")
            return False
            
        # 有效成语
        self.last_idiom = idiom
        self.used_idioms.append(idiom)
        
        # 更新分数
        if self.current_player == 1:
            self.score_player1 += 10
        else:
            self.score_player2 += 10
            
        # 重置计时器
        self.timer = 30
        
        # 显示成功消息
        if self.game_mode == "single":
            self.show_message(f"你: {idiom}")
        elif self.game_mode == "two_player":
            self.show_message(f"玩家{self.current_player}: {idiom}")
        else:
            self.show_message(f"玩家: {idiom}")
        
        # 切换玩家
        if self.game_mode == "two_player":
            self.current_player = 2 if self.current_player == 1 else 1
        elif self.game_mode == "ai" and self.current_player == 1:
            # AI回合
            self.ai_turn()
            
        return True
        
    def ai_turn(self):
        """AI回合"""
        if not self.last_idiom:
            return
            
        last_char = self.last_idiom[-1]
        possible_idioms = [idiom for idiom in idioms 
                          if idiom.startswith(last_char) and idiom not in self.used_idioms]
        
        if possible_idioms:
            time.sleep(1)  # AI思考时间
            
            ai_idiom = random.choice(possible_idioms)
            self.last_idiom = ai_idiom
            self.used_idioms.append(ai_idiom)
            self.score_player2 += 10
            self.timer = 30
            self.show_message(f"AI: {ai_idiom}")
            self.current_player = 1
        else:
            # AI无法接龙
            self.game_over("玩家获胜！AI无法接龙。")
            
    def game_over(self, message):
        """游戏结束"""
        self.state = "game_over"
        self.show_message(message)
        
    def update(self):
        """更新游戏状态"""
        current_time = time.time()
        
        # 清除过期的消息
        if self.message and current_time - self.message_time > 3:
            self.message = ""
            
        # 更新时间
        if self.state == "playing":
            time_passed = current_time - self.last_time
            if time_passed >= 1:
                self.timer -= 1
                self.last_time = current_time
                
                # 检查超时
                if self.timer <= 0:
                    if self.game_mode == "single":
                        self.game_over("时间到！游戏结束。")
                    elif self.game_mode == "two_player":
                        winner = "玩家2" if self.current_player == 1 else "玩家1"
                        self.game_over(f"时间到！{winner}获胜！")
                    elif self.game_mode == "ai":
                        if self.current_player == 1:
                            self.game_over("时间到！AI获胜！")
                        else:
                            self.game_over("时间到！玩家获胜！")
        
        # 更新输入框
        self.input_box.update()
                
    def draw_menu(self, surface):
        """绘制菜单"""
        # 绘制背景
        surface.fill(BACKGROUND_COLOR)
        
        # 绘制标题
        try:
            title = font_huge.render("成语接龙大挑战", True, TEXT_GOLD)
            surface.blit(title, (SCREEN_WIDTH//2 - title.get_width()//2, 150))
        except:
            # 如果标题渲染失败，绘制简单矩形
            pygame.draw.rect(surface, TEXT_GOLD, (SCREEN_WIDTH//2 - 200, 150, 400, 60), border_radius=10)
        
        # 绘制副标题
        try:
            subtitle = font_medium.render("挑战你的成语词汇量！", True, TEXT_BLUE)
            surface.blit(subtitle, (SCREEN_WIDTH//2 - subtitle.get_width()//2, 220))
        except:
            pass
        
        # 绘制按钮
        for button in self.buttons:
            button.draw(surface)
            
        # 绘制说明
        instructions = [
            "游戏规则：",
            "1. 每个成语必须是4个字",
            "2. 新成语的首字必须与上一个成语的尾字相同",
            "3. 不能重复使用已经用过的成语",
            "4. 每个玩家有30秒的思考时间"
        ]
        
        for i, instruction in enumerate(instructions):
            try:
                inst_text = font_small.render(instruction, True, TEXT_WHITE)
                surface.blit(inst_text, (50, 450 + i * 30))
            except:
                pass
            
    def draw_game(self, surface):
        """绘制游戏界面"""
        # 绘制背景
        surface.fill(BACKGROUND_COLOR)
        
        # 绘制游戏标题
        try:
            title = font_large.render("成语接龙", True, TEXT_GOLD)
            surface.blit(title, (SCREEN_WIDTH//2 - title.get_width()//2, 20))
        except:
            pass
        
        # 绘制当前玩家
        if self.game_mode == "single":
            player_text = "你的回合"
            player_color = PLAYER_1_COLOR
        elif self.game_mode == "two_player":
            player_text = f"玩家{self.current_player}的回合"
            player_color = PLAYER_1_COLOR if self.current_player == 1 else PLAYER_2_COLOR
        else:  # ai模式
            player_text = "你的回合" if self.current_player == 1 else "AI思考中..."
            player_color = PLAYER_1_COLOR if self.current_player == 1 else AI_COLOR
            
        try:
            player_surf = font_medium.render(player_text, True, player_color)
            surface.blit(player_surf, (SCREEN_WIDTH//2 - player_surf.get_width()//2, 70))
        except:
            pass
        
        # 绘制计时器
        timer_color = TEXT_GREEN if self.timer > 10 else TEXT_RED
        try:
            timer_text = font_large.render(f"时间: {self.timer}秒", True, timer_color)
            surface.blit(timer_text, (SCREEN_WIDTH - 200, 20))
        except:
            pass
        
        # 绘制分数
        if self.game_mode == "single":
            try:
                score_text = font_medium.render(f"分数: {self.score_player1}", True, TEXT_GOLD)
                surface.blit(score_text, (50, 20))
            except:
                pass
        elif self.game_mode == "two_player":
            try:
                score1_text = font_medium.render(f"玩家1: {self.score_player1}", True, PLAYER_1_COLOR)
                score2_text = font_medium.render(f"玩家2: {self.score_player2}", True, PLAYER_2_COLOR)
                surface.blit(score1_text, (50, 20))
                surface.blit(score2_text, (SCREEN_WIDTH - 200, 70))
            except:
                pass
        else:  # ai模式
            try:
                score1_text = font_medium.render(f"玩家: {self.score_player1}", True, PLAYER_1_COLOR)
                score2_text = font_medium.render(f"AI: {self.score_player2}", True, AI_COLOR)
                surface.blit(score1_text, (50, 20))
                surface.blit(score2_text, (SCREEN_WIDTH - 200, 70))
            except:
                pass
        
        # 绘制上一个成语
        if self.last_idiom:
            try:
                last_idiom_text = font_large.render(f"上一个成语: {self.last_idiom}", True, TEXT_GOLD)
                surface.blit(last_idiom_text, (SCREEN_WIDTH//2 - last_idiom_text.get_width()//2, 120))
                
                # 显示接龙要求
                requirement_text = font_medium.render(f"请以 '{self.last_idiom[-1]}' 开头", True, TEXT_BLUE)
                surface.blit(requirement_text, (SCREEN_WIDTH//2 - requirement_text.get_width()//2, 160))
            except:
                pass
            
        # 绘制输入框
        self.input_box.draw(surface)
        
        # 绘制提交按钮
        submit_button = Button(670, 450, 100, 60, "提交", None, BUTTON_COLOR)
        submit_button.draw(surface)
        
        # 绘制提示按钮
        hint_button = Button(780, 450, 100, 60, "提示", None, BUTTON_COLOR)
        hint_button.draw(surface)
        
        # 绘制历史记录
        self.draw_history(surface)
        
        # 绘制消息
        if self.message:
            try:
                message_bg = pygame.Rect(SCREEN_WIDTH//2 - 200, 520, 400, 40)
                pygame.draw.rect(surface, (40, 60, 80, 200), message_bg, border_radius=10)
                
                message_text = font_medium.render(self.message, True, TEXT_GREEN)
                surface.blit(message_text, (SCREEN_WIDTH//2 - message_text.get_width()//2, 530))
            except:
                pass
            
    def draw_history(self, surface):
        """绘制历史记录"""
        # 创建历史记录背景
        history_bg = pygame.Rect(50, 200, 300, 350)
        pygame.draw.rect(surface, (30, 40, 60, 200), history_bg, border_radius=10)
        pygame.draw.rect(surface, (80, 100, 150), history_bg, 2, border_radius=10)
        
        # 绘制标题
        try:
            history_title = font_medium.render("历史记录", True, TEXT_WHITE)
            surface.blit(history_title, (200 - history_title.get_width()//2, 210))
        except:
            pass
        
        # 绘制历史记录
        start_index = max(0, len(self.used_idioms) - 8)  # 显示最后8条记录
        for i, idiom in enumerate(self.used_idioms[start_index:]):
            y_pos = 260 + i * 30
            index = start_index + i + 1
            
            try:
                history_text = font_small.render(f"{index}. {idiom}", True, TEXT_WHITE)
                surface.blit(history_text, (70, y_pos))
            except:
                pass
                
    def draw_game_over(self, surface):
        """绘制游戏结束界面"""
        # 半透明背景
        overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 180))
        surface.blit(overlay, (0, 0))
        
        # 游戏结束标题
        try:
            game_over_text = font_huge.render("游戏结束", True, TEXT_RED)
            surface.blit(game_over_text, (SCREEN_WIDTH//2 - game_over_text.get_width()//2, 150))
        except:
            pass
        
        # 绘制最终分数
        if self.game_mode == "single":
            try:
                score_text = font_large.render(f"最终分数: {self.score_player1}", True, TEXT_GOLD)
                surface.blit(score_text, (SCREEN_WIDTH//2 - score_text.get_width()//2, 250))
            except:
                pass
        elif self.game_mode == "two_player":
            try:
                score1_text = font_large.render(f"玩家1: {self.score_player1}", True, PLAYER_1_COLOR)
                score2_text = font_large.render(f"玩家2: {self.score_player2}", True, PLAYER_2_COLOR)
                surface.blit(score1_text, (SCREEN_WIDTH//2 - 200, 250))
                surface.blit(score2_text, (SCREEN_WIDTH//2 + 50, 250))
            except:
                pass
        else:  # ai模式
            try:
                score1_text = font_large.render(f"玩家: {self.score_player1}", True, PLAYER_1_COLOR)
                score2_text = font_large.render(f"AI: {self.score_player2}", True, AI_COLOR)
                surface.blit(score1_text, (SCREEN_WIDTH//2 - 200, 250))
                surface.blit(score2_text, (SCREEN_WIDTH//2 + 50, 250))
            except:
                pass
        
        # 绘制按钮
        button_width, button_height = 200, 60
        
        restart_button = Button(SCREEN_WIDTH//2 - button_width - 100, 450, button_width, button_height, 
                              "重新开始", lambda: self.start_game(self.game_mode))
        menu_button = Button(SCREEN_WIDTH//2 - button_width//2, 450, button_width, button_height, 
                           "返回菜单", lambda: setattr(self, 'state', "menu"))
        quit_button = Button(SCREEN_WIDTH//2 + 100, 450, button_width, button_height, 
                           "退出游戏", self.quit_game)
        
        mouse_pos = pygame.mouse.get_pos()
        restart_button.check_hover(mouse_pos)
        menu_button.check_hover(mouse_pos)
        quit_button.check_hover(mouse_pos)
        
        restart_button.draw(surface)
        menu_button.draw(surface)
        quit_button.draw(surface)
            
    def handle_events(self):
        """处理事件"""
        mouse_pos = pygame.mouse.get_pos()
        
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
                
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    if self.state == "playing":
                        self.state = "menu"
                    elif self.state == "game_over":
                        self.state = "menu"
                        
                elif self.state == "playing":
                    # 处理输入框
                    result = self.input_box.handle_event(event)
                    if result is not None and result:
                        self.submit_idiom(result)
                        self.input_box.text = ""
                        
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:  # 左键点击
                    if self.state == "menu":
                        for button in self.buttons:
                            action = button.check_click(mouse_pos)
                            if action:
                                action()
                                
                    elif self.state == "playing":
                        # 检查提交按钮
                        if 670 <= mouse_pos[0] <= 770 and 450 <= mouse_pos[1] <= 510:
                            self.submit_idiom(self.input_box.text)
                            self.input_box.text = ""
                            
                        # 检查提示按钮
                        elif 780 <= mouse_pos[0] <= 880 and 450 <= mouse_pos[1] <= 510:
                            if self.last_idiom:
                                last_char = self.last_idiom[-1]
                                hints = [idiom for idiom in idioms 
                                        if idiom.startswith(last_char) and idiom not in self.used_idioms]
                                if hints:
                                    hint = random.choice(hints[:3])
                                    self.show_message(f"提示：可以试试 '{hint}'")
                                else:
                                    self.show_message("提示：无可用成语")
                                
                    elif self.state == "game_over":
                        if 200 <= mouse_pos[0] <= 400 and 450 <= mouse_pos[1] <= 510:
                            self.start_game(self.game_mode)
                        elif 400 <= mouse_pos[0] <= 600 and 450 <= mouse_pos[1] <= 510:
                            self.state = "menu"
                        elif 600 <= mouse_pos[0] <= 800 and 450 <= mouse_pos[1] <= 510:
                            self.quit_game()
                            
            elif event.type == pygame.MOUSEMOTION:
                if self.state == "menu":
                    for button in self.buttons:
                        button.check_hover(mouse_pos)
                        
    def draw(self, surface):
        """绘制整个游戏"""
        if self.state == "menu":
            self.draw_menu(surface)
        elif self.state == "playing":
            self.draw_game(surface)
        elif self.state == "game_over":
            self.draw_game_over(surface)

def main():
    game = IdiomGame()
    
    while True:
        game.handle_events()
        game.update()
        game.draw(screen)
        pygame.display.flip()
        clock.tick(FPS)

if __name__ == "__main__":
    main()