import pygame
import sys

# --- 1. 初始化 ---
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("成语接龙 (兼容版)")
clock = pygame.time.Clock()

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BLUE = (0, 102, 204)
GREEN = (0, 153, 76)
RED = (204, 0, 0)
GRAY = (245, 245, 245)

# 字体加载 - 尝试多种常见中文字体名以确保兼容
def get_font(size):
    fonts = ["SimHei", "Microsoft YaHei", "Arial Unicode MS", "SimSun"]
    for f in fonts:
        try:
            return pygame.font.SysFont(f, size)
        except:
            continue
    return pygame.font.SysFont(None, size)

font_title = get_font(40)
font_text = get_font(28)
font_small = get_font(20)

# --- 2. 游戏数据 ---
history = ["一心一意"]  # 初始成语
input_text = ""        # 当前输入的文字
message = "请切换中文输入法，输入成语并按回车"
msg_color = BLACK

def validate_idiom(new_word, last_word):
    """校验逻辑"""
    if len(new_word) != 4:
        return False, "请输入四个字的成语！"
    if new_word[0] != last_word[-1]:
        return False, f"首字不对！应以 '{last_word[-1]}' 开头"
    return True, "接龙成功！"

# --- 3. 主循环 ---
running = True

while running:
    screen.fill(WHITE)
    
    # --- 4. 事件处理 ---
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        
        elif event.type == pygame.KEYDOWN:
            # 处理退格键
            if event.key == pygame.K_BACKSPACE:
                input_text = input_text[:-1]
            
            # 处理回车键 (提交)
            elif event.key == pygame.K_RETURN:
                if input_text:
                    success, msg = validate_idiom(input_text, history[-1])
                    if success:
                        history.append(input_text)
                        input_text = ""
                        message = msg
                        msg_color = GREEN
                        if len(history) > 10:
                            history.pop(0)
                    else:
                        message = msg
                        msg_color = RED
            
            # 处理文字输入 (兼容中文输入法)
            else:
                # event.unicode 包含了输入法合成后的汉字
                char = event.unicode
                if char and char.isprintable():
                    if len(input_text) < 4:
                        input_text += char

    # --- 5. 绘制界面 ---
    
    # 标题
    title_surf = font_title.render("成语接龙游戏", True, BLUE)
    screen.blit(title_surf, (300, 30))
    
    # 历史记录背景
    pygame.draw.rect(screen, GRAY, (100, 80, 600, 380))
    pygame.draw.rect(screen, BLACK, (100, 80, 600, 380), 2)
    
    # 绘制成语列表
    for i, word in enumerate(history):
        # 最后一个词用蓝色加重显示
        is_last = (i == len(history) - 1)
        color = BLUE if is_last else BLACK
        prefix = ">> " if is_last else "  "
        h_surf = font_text.render(f"{prefix}{word}", True, color)
        screen.blit(h_surf, (120, 95 + i * 35))

    # 提示信息
    msg_surf = font_small.render(message, True, msg_color)
    screen.blit(msg_surf, (100, 470))

    # 输入框绘制
    input_rect = pygame.Rect(100, 500, 600, 50)
    pygame.draw.rect(screen, WHITE, input_rect)
    pygame.draw.rect(screen, BLUE, input_rect, 2)
    
    # 渲染当前输入的文字
    input_display = font_text.render(input_text, True, BLACK)
    screen.blit(input_display, (110, 510))
    
    # 光标闪烁效果
    if pygame.time.get_ticks() % 1000 < 500:
        cursor_x = 115 + font_text.size(input_text)[0]
        pygame.draw.line(screen, BLACK, (cursor_x, 512), (cursor_x, 538), 2)

    # 底部操作提示
    tip_text = "操作说明：在窗口内直接打字（若无选词框请盲打），按回车提交"
    tip_surf = font_small.render(tip_text, True, (120, 120, 120))
    screen.blit(tip_surf, (100, 560))

    pygame.display.flip()
    clock.tick(30)

pygame.quit()
sys.exit()