import pygame
import sys
import random
import os

pygame.init()
W, H = 680, 450
screen = pygame.display.set_mode((W, H))
pygame.display.set_caption("成语接龙")
clock = pygame.time.Clock()

# 颜色
WHITE = (255,255,255)
BLACK = (0,0,0)
GREEN = (22,155,55)
RED = (210,20,20)
BLUE = (15,85,210)

# ==========中文字体修复核心代码==========
try:
    # Windows系统黑体，绝大多数电脑自带
    font_path = "C:/Windows/Fonts/simhei.ttf"
    font_big = pygame.font.Font(font_path, 44)
    font_mid = pygame.font.Font(font_path, 32)
    font_small = pygame.font.Font(font_path, 26)
except:
    # 找不到中文字体自动切内置英文（不会报错）
    font_big = pygame.font.Font(None,44)
    font_mid = pygame.font.Font(None,32)
    font_small = pygame.font.Font(None,26)

# 成语词库
idiom_list = [
    "一帆风顺","四面八方","方寸之地","地久天长","长治久安",
    "安安稳稳","稳扎稳打","打草惊蛇","蛇蝎心肠","长驱直入",
    "入木三分","分秒必争","争先恐后","后来居上","上天入地",
    "地大物博","博古通今","今非昔比","比比皆是","是非分明"
]

# 游戏数据
start_idiom = random.choice(idiom_list)
last_char = start_idiom[-1]
user_input = ""
msg = f"起始成语：{start_idiom}，请输入以【{last_char}】开头的成语"
score = 0

running = True
while running:
    screen.fill(WHITE)
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            running = False
        if e.type == pygame.KEYDOWN:
            if e.key == pygame.K_BACKSPACE:
                user_input = user_input[:-1]
            elif e.key == pygame.K_RETURN:
                # 答案判定
                if len(user_input)>=2 and user_input[0]==last_char and user_input in idiom_list:
                    score +=10
                    last_char = user_input[-1]
                    msg = f"回答正确！下一个首字：【{last_char}】 当前分数：{score}"
                else:
                    msg = f"回答错误！仍需要以【{last_char}】开头，当前分数：{score}"
                user_input = ""
            else:
                # 接收中文输入法输入汉字
                user_input += e.unicode

    # 绘制内容
    title = font_big.render("成语接龙小游戏",True,GREEN)
    screen.blit(title,(W//2-title.get_width()//2,15))

    info_text = font_mid.render(msg,True,BLACK)
    screen.blit(info_text,(25,85))

    # 输入框
    pygame.draw.rect(screen,(240,240,240),(25,145,630,58))
    input_render = font_mid.render(user_input,True,BLUE)
    screen.blit(input_render,(35,155))

    tip_text = font_small.render("回车键提交答案｜退格删除文字｜输入法直接打汉字",True,RED)
    screen.blit(tip_text,(25,230))

    score_text = font_mid.render(f"当前得分：{score}",True,GREEN)
    screen.blit(score_text,(25,300))

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

pygame.quit()
sys.exit()