# -*- coding: utf-8 -*-
# 007特工驾驶小游戏 | 纯绘制无外部资源 | 最终稳定版
# 适配 pygame 2.6.1 + Python 3.8 修复字体报错
# 操作：左右方向键移动 | 空格发射导弹 | R键重新开始
import pygame
import random

# ==============================
# 系统初始化模块 【代码行：1 - 46】
# ==============================
pygame.init()

# 窗口尺寸
SCREEN_WIDTH = 400
SCREEN_HEIGHT = 600
game_screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("007 Agent Racing")

# 帧率控制
FRAME_RATE = 60
game_clock = pygame.time.Clock()

# 颜色定义
COLOR_BLACK = (0, 0, 0)
COLOR_WHITE = (255, 255, 255)
COLOR_ROAD = (42, 42, 42)
COLOR_ROAD_LINE = (230, 230, 0)
COLOR_PLAYER_CAR = (8, 115, 210)
COLOR_ENEMY_CAR = (210, 15, 15)
COLOR_WINDOW = (18, 18, 18)
COLOR_WHEEL = (5, 5, 5)
COLOR_HEADLIGHT = (255, 252, 190)
COLOR_ITEM_SPEED = (18, 225, 18)
COLOR_ITEM_SHIELD = (25, 175, 255)
COLOR_ITEM_MISSILE = (255, 135, 0)
COLOR_SHIELD_EFFECT = (95, 195, 250)
COLOR_TEXT_SCORE = (255, 255, 255)
COLOR_TEXT_MISSILE = (255, 205, 0)
COLOR_TEXT_LEVEL = (0, 255, 255)
COLOR_TEXT_TIP = (200, 200, 200)
COLOR_GAMEOVER_BG = (15, 15, 15)
COLOR_GAMEOVER_TEXT = (255, 45, 45)

# 物体尺寸
CAR_WIDTH = 42
CAR_HEIGHT = 82
ITEM_WIDTH = 32
ITEM_HEIGHT = 32
WHEEL_RADIUS = 7
HEADLIGHT_RADIUS = 4
LINE_WIDTH = 4
LINE_BLOCK_HEIGHT = 30
LINE_GAP = 25

# ==============================
# 全局变量模块 【代码行：47 - 96】
# ==============================
# 玩家车辆
player_pos_x = SCREEN_WIDTH // 2 - CAR_WIDTH // 2
player_pos_y = SCREEN_HEIGHT - 110
player_base_speed = 5
player_current_speed = player_base_speed

# 敌方车辆
enemy_car_list = []
enemy_base_move_speed = 3.4
enemy_current_speed = enemy_base_move_speed
enemy_spawn_timer = 0
enemy_spawn_interval = 46
enemy_min_spawn_interval = 12

# 道具系统
game_item_list = []
item_falling_speed = 2.7
speed_effect_duration = 180
shield_effect_duration = 300
speed_effect_timer = 0
shield_effect_timer = 0
missile_total_count = 0

# 分数等级
game_score = 0
game_level = 1
level_up_standard = 50

# 赛道滚动
road_scroll_line_y = 0

# 游戏状态
is_game_over = False
game_main_loop_running = True

# ========== 核心修复：改用标准 Font 接口，彻底解决字体类型报错 ==========
font_tiny = pygame.font.Font(None, 20)
font_small = pygame.font.Font(None, 24)
font_medium = pygame.font.Font(None, 30)
font_large = pygame.font.Font(None, 42)
font_huge = pygame.font.Font(None, 50)

# ==============================
# 绘图函数模块 【代码行：97 - 382】
# ==============================
def draw_racing_road():
    """绘制滚动赛道"""
    global road_scroll_line_y
    game_screen.fill(COLOR_ROAD)
    pygame.draw.rect(game_screen, COLOR_WHITE, (0, 0, 8, SCREEN_HEIGHT))
    pygame.draw.rect(game_screen, COLOR_WHITE, (SCREEN_WIDTH - 8, 0, 8, SCREEN_HEIGHT))
    road_scroll_line_y += 3
    if road_scroll_line_y > LINE_BLOCK_HEIGHT + LINE_GAP:
        road_scroll_line_y = 0
    for y_pos in range(-LINE_BLOCK_HEIGHT, SCREEN_HEIGHT, LINE_BLOCK_HEIGHT + LINE_GAP):
        draw_y = y_pos + road_scroll_line_y
        pygame.draw.rect(
            game_screen,
            COLOR_ROAD_LINE,
            (SCREEN_WIDTH // 2 - LINE_WIDTH // 2, draw_y, LINE_WIDTH, LINE_BLOCK_HEIGHT)
        )

def draw_player_vehicle(x, y):
    """绘制玩家跑车"""
    pygame.draw.rect(game_screen, COLOR_PLAYER_CAR, (x, y, CAR_WIDTH, CAR_HEIGHT), 0)
    pygame.draw.rect(game_screen, COLOR_WINDOW, (x + 8, y + 15, CAR_WIDTH - 16, 28), 0)
    pygame.draw.circle(game_screen, COLOR_WHEEL, (x + 9, y + 10), WHEEL_RADIUS)
    pygame.draw.circle(game_screen, COLOR_WHEEL, (x + CAR_WIDTH - 9, y + 10), WHEEL_RADIUS)
    pygame.draw.circle(game_screen, COLOR_WHEEL, (x + 9, y + CAR_HEIGHT - 10), WHEEL_RADIUS)
    pygame.draw.circle(game_screen, COLOR_WHEEL, (x + CAR_WIDTH - 9, y + CAR_HEIGHT - 10), WHEEL_RADIUS)
    pygame.draw.circle(game_screen, COLOR_HEADLIGHT, (x + 12, y + 5), HEADLIGHT_RADIUS)
    pygame.draw.circle(game_screen, COLOR_HEADLIGHT, (x + CAR_WIDTH - 12, y + 5), HEADLIGHT_RADIUS)

def draw_enemy_vehicle(x, y):
    """绘制敌方车辆"""
    pygame.draw.rect(game_screen, COLOR_ENEMY_CAR, (x, y, CAR_WIDTH, CAR_HEIGHT), 0)
    pygame.draw.rect(game_screen, COLOR_WINDOW, (x + 8, y + 15, CAR_WIDTH - 16, 28), 0)
    pygame.draw.circle(game_screen, COLOR_WHEEL, (x + 9, y + 10), WHEEL_RADIUS)
    pygame.draw.circle(game_screen, COLOR_WHEEL, (x + CAR_WIDTH - 9, y + 10), WHEEL_RADIUS)
    pygame.draw.circle(game_screen, COLOR_WHEEL, (x + 9, y + CAR_HEIGHT - 10), WHEEL_RADIUS)
    pygame.draw.circle(game_screen, COLOR_WHEEL, (x + CAR_WIDTH - 9, y + CAR_HEIGHT - 10), WHEEL_RADIUS)

def draw_game_item(x, y, item_type):
    """绘制游戏道具"""
    center_x = x + ITEM_WIDTH // 2
    center_y = y + ITEM_HEIGHT // 2
    if item_type == "speed":
        pygame.draw.circle(game_screen, COLOR_ITEM_SPEED, (center_x, center_y), ITEM_WIDTH // 2)
        text_label = font_small.render("SPD", True, COLOR_WHITE)
        game_screen.blit(text_label, (x + 4, y + 4))
    elif item_type == "shield":
        pygame.draw.circle(game_screen, COLOR_ITEM_SHIELD, (center_x, center_y), ITEM_WIDTH // 2)
        text_label = font_small.render("SHD", True, COLOR_WHITE)
        game_screen.blit(text_label, (x + 4, y + 4))
    elif item_type == "missile":
        pygame.draw.circle(game_screen, COLOR_ITEM_MISSILE, (center_x, center_y), ITEM_WIDTH // 2)
        text_label = font_small.render("MSL", True, COLOR_WHITE)
        game_screen.blit(text_label, (x + 4, y + 4))

def draw_shield_ring(x, y):
    """绘制护盾光环"""
    car_center_x = x + CAR_WIDTH // 2
    car_center_y = y + CAR_HEIGHT // 2
    pygame.draw.circle(game_screen, COLOR_SHIELD_EFFECT, (car_center_x, car_center_y), 52, 4)

def draw_game_ui():
    """绘制界面UI"""
    score_display = font_medium.render(f"SCORE: {game_score}", True, COLOR_TEXT_SCORE)
    game_screen.blit(score_display, (12, 10))
    missile_display = font_medium.render(f"MISSILE: {missile_total_count}", True, COLOR_TEXT_MISSILE)
    game_screen.blit(missile_display, (12, 45))
    level_display = font_medium.render(f"LV: {game_level}", True, COLOR_TEXT_LEVEL)
    game_screen.blit(level_display, (SCREEN_WIDTH - 100, 10))
    tip_y_pos = 80
    if speed_effect_timer > 0:
        speed_tip = font_small.render("SPEED UP!", True, COLOR_ITEM_SPEED)
        game_screen.blit(speed_tip, (12, tip_y_pos))
        tip_y_pos += 25
    if shield_effect_timer > 0:
        shield_tip = font_small.render("SHIELD ON!", True, COLOR_ITEM_SHIELD)
        game_screen.blit(shield_tip, (12, tip_y_pos))

def draw_game_over_interface():
    """游戏结束界面"""
    mask_surface = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
    mask_surface.set_alpha(180)
    mask_surface.fill(COLOR_GAMEOVER_BG)
    game_screen.blit(mask_surface, (0, 0))
    center_x = SCREEN_WIDTH // 2
    center_y = SCREEN_HEIGHT // 2
    over_title = font_huge.render("GAME OVER", True, COLOR_GAMEOVER_TEXT)
    game_screen.blit(over_title, (center_x - 110, center_y - 90))
    final_score_text = font_medium.render(f"FINAL SCORE: {game_score}", True, COLOR_WHITE)
    game_screen.blit(final_score_text, (center_x - 85, center_y - 20))
    restart_tip = font_medium.render("PRESS R TO RESTART", True, COLOR_WHITE)
    game_screen.blit(restart_tip, (center_x - 130, center_y + 30))
    quit_tip = font_tiny.render("CLOSE WINDOW TO EXIT", True, COLOR_TEXT_TIP)
    game_screen.blit(quit_tip, (center_x - 95, center_y + 70))

# ==============================
# 逻辑函数模块 【代码行：383 - 622】
# ==============================
def full_game_reset():
    """重置游戏"""
    global player_pos_x, player_pos_y, player_current_speed
    global enemy_car_list, enemy_current_speed, enemy_spawn_timer, enemy_spawn_interval
    global game_item_list, speed_effect_timer, shield_effect_timer, missile_total_count
    global game_score, game_level, is_game_over, road_scroll_line_y

    player_pos_x = SCREEN_WIDTH // 2 - CAR_WIDTH // 2
    player_pos_y = SCREEN_HEIGHT - 110
    player_current_speed = player_base_speed

    enemy_car_list.clear()
    enemy_current_speed = enemy_base_move_speed
    enemy_spawn_timer = 0
    enemy_spawn_interval = 46

    game_item_list.clear()
    speed_effect_timer = 0
    shield_effect_timer = 0
    missile_total_count = 0

    game_score = 0
    game_level = 1
    is_game_over = False
    road_scroll_line_y = 0

def spawn_new_enemy_car():
    """生成敌方车辆"""
    random_x = random.randint(10, SCREEN_WIDTH - CAR_WIDTH - 10)
    enemy_car_list.append([random_x, -CAR_HEIGHT])

def spawn_random_game_item():
    """生成随机道具"""
    item_type_pool = ["speed", "shield", "missile"]
    selected_type = random.choice(item_type_pool)
    random_x = random.randint(10, SCREEN_WIDTH - ITEM_WIDTH - 10)
    game_item_list.append([random_x, -ITEM_HEIGHT, selected_type])

def rectangle_collision_detection(rect_a, rect_b):
    """矩形碰撞检测"""
    a_x, a_y, a_w, a_h = rect_a
    b_x, b_y, b_w, b_h = rect_b
    if a_x < b_x + b_w and a_x + a_w > b_x and a_y < b_y + b_h and a_y + a_h > b_y:
        return True
    return False

def update_game_difficulty():
    """动态提升难度"""
    global game_level, enemy_current_speed, enemy_spawn_interval
    current_new_level = game_score // level_up_standard + 1
    if current_new_level > game_level:
        game_level = current_new_level
    enemy_current_speed = enemy_base_move_speed + (game_level - 1) * 0.55
    enemy_spawn_interval = max(enemy_min_spawn_interval, 46 - (game_level - 1) * 4)

# ==============================
# 主循环模块 【代码行：623 - 994】
# ==============================
def game_main_loop():
    """游戏主循环"""
    global game_main_loop_running, is_game_over, enemy_spawn_timer, game_score
    global player_pos_x, player_current_speed, speed_effect_timer, shield_effect_timer
    global enemy_car_list, game_item_list, missile_total_count

    while game_main_loop_running:
        game_clock.tick(FRAME_RATE)

        # 事件监听
        for game_event in pygame.event.get():
            if game_event.type == pygame.QUIT:
                game_main_loop_running = False
            if is_game_over and game_event.type == pygame.KEYDOWN:
                if game_event.key == pygame.K_r:
                    full_game_reset()
            if not is_game_over and game_event.type == pygame.KEYDOWN:
                if game_event.key == pygame.K_SPACE and missile_total_count > 0:
                    missile_total_count -= 1
                    enemy_car_list.clear()

        if not is_game_over:
            draw_racing_road()
            update_game_difficulty()

            # 玩家移动
            key_state = pygame.key.get_pressed()
            if speed_effect_timer > 0:
                speed_effect_timer -= 1
                real_move_speed = player_current_speed + 3
            else:
                real_move_speed = player_current_speed

            if key_state[pygame.K_LEFT] and player_pos_x > 10:
                player_pos_x -= real_move_speed
            if key_state[pygame.K_RIGHT] and player_pos_x < SCREEN_WIDTH - CAR_WIDTH - 10:
                player_pos_x += real_move_speed

            if shield_effect_timer > 0:
                shield_effect_timer -= 1

            # 生成敌人
            enemy_spawn_timer += 1
            if enemy_spawn_timer >= enemy_spawn_interval:
                enemy_spawn_timer = 0
                spawn_new_enemy_car()
                if random.random() < 0.28:
                    spawn_random_game_item()

            player_collision_rect = (player_pos_x, player_pos_y, CAR_WIDTH, CAR_HEIGHT)

            # 更新敌方车辆
            for index in range(len(enemy_car_list) - 1, -1, -1):
                e_x, e_y = enemy_car_list[index]
                e_y += enemy_current_speed
                enemy_car_list[index][1] = e_y

                if e_y > SCREEN_HEIGHT:
                    enemy_car_list.pop(index)
                    game_score += 10
                    continue

                enemy_collision_rect = (e_x, e_y, CAR_WIDTH, CAR_HEIGHT)
                if rectangle_collision_detection(player_collision_rect, enemy_collision_rect):
                    if shield_effect_timer > 0:
                        enemy_car_list.pop(index)
                        shield_effect_timer = 0
                    else:
                        is_game_over = True
                draw_enemy_vehicle(e_x, e_y)

            # 更新道具
            for index in range(len(game_item_list) - 1, -1, -1):
                i_x, i_y, i_type = game_item_list[index]
                i_y += item_falling_speed
                game_item_list[index][1] = i_y

                if i_y > SCREEN_HEIGHT:
                    game_item_list.pop(index)
                    continue

                item_collision_rect = (i_x, i_y, ITEM_WIDTH, ITEM_HEIGHT)
                if rectangle_collision_detection(player_collision_rect, item_collision_rect):
                    game_item_list.pop(index)
                    if i_type == "speed":
                        speed_effect_timer = speed_effect_duration
                    elif i_type == "shield":
                        shield_effect_timer = shield_effect_duration
                    elif i_type == "missile":
                        missile_total_count += 1
                    continue
                draw_game_item(i_x, i_y, i_type)

            draw_player_vehicle(player_pos_x, player_pos_y)
            if shield_effect_timer > 0:
                draw_shield_ring(player_pos_x, player_pos_y)
            draw_game_ui()

        else:
            draw_game_over_interface()

        pygame.display.flip()

# ==============================
# 程序入口 【代码行：995 - 1004】
# ==============================
if __name__ == "__main__":
    game_main_loop()
    pygame.quit()