import pygame
import random
import sys

# 1. 初始化 Pygame
pygame.init()

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (30, 30, 30)
RED = (255, 80, 80)
GREEN = (0, 200, 0)
BLUE = (0, 120, 215)
GRAY = (200, 200, 200)

# 屏幕设置
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("极速打字练习")

# 字体加载
font_word = pygame.font.SysFont("Consolas", 32, bold=True)
font_ui = pygame.font.SysFont("SimHei", 24)

# 单词库
WORDS = ["python", "pygame", "coding", "algorithm", "variable", "function", 
         "keyboard", "display", "render", "update", "integer", "boolean",
         "string", "constant", "dynamic", "interface", "system", "logic"]

# 游戏变量
falling_words = []  # 存储当前屏幕上的单词对象
current_input = ""  # 当前输入的字符串
score = 0
missed = 0
speed = 1.5         # 初始掉落速度
spawn_delay = 1500  # 生成新单词的时间间隔 (毫秒)
last_spawn_time = pygame.time.get_ticks()

class Word:
    def __init__(self):
        self.text = random.choice(WORDS)
        self.x = random.randint(50, WIDTH - 150)
        self.y = -20
        self.color = BLACK

    def move(self):
        self.y += speed

    def draw(self):
        # 绘制单词
        word_surf = font_word.render(self.text, True, self.color)
        screen.blit(word_surf, (self.x, self.y))

def reset_game():
    global score, missed, speed, falling_words, current_input
    score = 0
    missed = 0
    speed = 1.5
    falling_words = []
    current_input = ""

# 主循环
clock = pygame.time.Clock()
game_over = False

while True:
    screen.fill(WHITE)
    
    if not game_over:
        current_time = pygame.time.get_ticks()

        # --- 1. 生成新单词 ---
        if current_time - last_spawn_time > spawn_delay:
            falling_words.append(Word())
            last_spawn_time = current_time
            # 随着分数增加，逐渐加快速度
            speed = 1.5 + (score // 5) * 0.2

        # --- 2. 事件处理 ---
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_BACKSPACE:
                    current_input = current_input[:-1]
                elif event.key == pygame.K_SPACE or event.key == pygame.K_RETURN:
                    # 检查是否匹配成功
                    matched = False
                    for word in falling_words:
                        if current_input == word.text:
                            falling_words.remove(word)
                            score += 1
                            matched = True
                            break
                    current_input = "" # 清空输入框
                else:
                    # 记录输入的字母
                    if event.unicode.isalpha():
                        current_input += event.unicode

        # --- 3. 更新单词位置 ---
        for word in falling_words[:]:
            word.move()
            # 检查是否触底
            if word.y > HEIGHT - 80:
                falling_words.remove(word)
                missed += 1
                if missed >= 10: # 漏掉10个单词则游戏结束
                    game_over = True

        # --- 4. 绘制画面 ---
        # 绘制单词
        for word in falling_words:
            word.draw()

        # 绘制底部输入区域
        pygame.draw.rect(screen, GRAY, (0, HEIGHT - 60, WIDTH, 60))
        pygame.draw.line(screen, BLACK, (0, HEIGHT - 60), (WIDTH, HEIGHT - 60), 2)
        
        input_label = font_ui.render("当前输入: ", True, BLACK)
        screen.blit(input_label, (20, HEIGHT - 40))
        
        input_surf = font_word.render(current_input, True, BLUE)
        screen.blit(input_surf, (150, HEIGHT - 45))

        # 绘制得分
        score_surf = font_ui.render(f"得分: {score}  漏掉: {missed}/10", True, BLACK)
        screen.blit(score_surf, (20, 20))

    else:
        # --- 游戏结束画面 ---
        over_surf = font_word.render("游戏结束!", True, RED)
        final_score = font_ui.render(f"最终得分: {score}", True, BLACK)
        restart_hint = font_ui.render("按 R 键重新开始", True, BLUE)
        
        screen.blit(over_surf, (WIDTH//2 - 80, HEIGHT//2 - 50))
        screen.blit(final_score, (WIDTH//2 - 60, HEIGHT//2 + 10))
        screen.blit(restart_hint, (WIDTH//2 - 80, HEIGHT//2 + 60))

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_r:
                    reset_game()
                    game_over = False

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