import pygame
import random
import sys
import time

# 初始化pygame
pygame.init()

# 游戏基础设置
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("驾驶小游戏 - 生命道具+商城续命版")

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
GRAY = (128, 128, 128)
LIGHT_BLUE = (173, 216, 230)
YELLOW = (255, 255, 0)
PURPLE = (128, 0, 128)
ORANGE = (255, 165, 0)  # 生命道具颜色

# ====================== 核心游戏变量 ======================
# 玩家设置
player_width = 50
player_height = 80
player_x = WIDTH // 2 - player_width // 2
player_y = HEIGHT - player_height - 20
player_speed = 8
original_speed = 8

# 生命系统（改为道具+商城购买）
lives = 3  # 初始生命
max_lives = 5  # 最大生命上限
life_price = 30  # 商城购买一条生命的价格

# 金币系统
coin = 0
coin_per_score = 1  # 每得1分奖励1金币

# 皮肤系统
skins = [
    {"name": "默认绿色", "color": GREEN, "price": 0, "unlocked": True},
    {"name": "火焰红", "color": RED, "price": 20, "unlocked": False},
    {"name": "黄金黄", "color": YELLOW, "price": 50, "unlocked": False},
    {"name": "电光紫", "color": PURPLE, "price": 100, "unlocked": False},
]
current_skin = 0  # 当前使用的皮肤索引

# 障碍物设置
obstacle_width = 50
obstacle_height = 80
obstacle_list = []
obstacle_speed = 6
obstacle_spawn_rate = 60

# 道具系统（新增生命道具）
prop_radius = 20
prop_list = []
prop_speed = 5
prop_spawn_rate = 150
PROP_TYPES = ["speed", "shield", "life"]  # 新增life道具

# 道具效果状态
speed_boost_active = False
speed_boost_end_time = 0
shield_active = False

# 游戏状态控制
score = 0
clock = pygame.time.Clock()
font = pygame.font.Font(None, 40)
game_state = "play"  # play:游戏中, shop:商城, gameover:生命为0

# ====================== 绘制函数 ======================
def draw_player(x, y):
    """绘制玩家车辆（带皮肤+护盾效果）"""
    skin_color = skins[current_skin]["color"]
    # 车身
    pygame.draw.rect(screen, skin_color, (x, y, player_width, player_height))
    # 车窗
    pygame.draw.rect(screen, WHITE, (x + 10, y + 10, player_width - 20, player_height // 3))
    # 护盾边框
    if shield_active:
        pygame.draw.rect(screen, LIGHT_BLUE, (x-5, y-5, player_width+10, player_height+10), 3)

def draw_obstacle(x, y):
    """绘制障碍物"""
    pygame.draw.rect(screen, RED, (x, y, obstacle_width, obstacle_height))

def draw_prop(x, y, prop_type):
    """绘制道具（加速/护盾/生命）"""
    # 道具颜色和图标
    if prop_type == "speed":
        color = GREEN
        icon = "S"
    elif prop_type == "shield":
        color = BLUE
        icon = "H"
    elif prop_type == "life":
        color = ORANGE
        icon = "L"
    
    # 绘制圆形道具
    pygame.draw.circle(screen, color, (x + prop_radius, y + prop_radius), prop_radius)
    # 绘制道具图标文字
    prop_text = font.render(icon, True, WHITE)
    text_rect = prop_text.get_rect(center=(x + prop_radius, y + prop_radius))
    screen.blit(prop_text, text_rect)

def draw_game_ui():
    """绘制游戏界面UI（分数、生命、金币、道具状态）"""
    # 分数
    score_text = font.render(f"分数: {score}", True, BLACK)
    screen.blit(score_text, (10, 10))
    # 生命
    life_text = font.render(f"生命: {lives}", True, ORANGE)
    screen.blit(life_text, (10, 50))
    # 金币
    coin_text = font.render(f"金币: {coin}", True, YELLOW)
    screen.blit(coin_text, (10, 90))
    # 商城提示
    shop_text = font.render("按S进入商城", True, BLUE)
    screen.blit(shop_text, (10, 130))
    
    # 加速状态
    if speed_boost_active:
        remaining_time = max(0, int(speed_boost_end_time - time.time()))
        speed_text = font.render(f"加速: {remaining_time}s", True, GREEN)
        screen.blit(speed_text, (180, 10))
    # 护盾状态（修复笔误）
    if shield_active:
        shield_text = font.render("护盾: 激活", True, BLUE)
        screen.blit(shield_text, (180, 50))

# ====================== 核心逻辑函数 ======================
def check_collision(rect1, rect2):
    """碰撞检测"""
    return rect1.colliderect(rect2)

def handle_prop_pickup(player_rect):
    """处理道具拾取"""
    global speed_boost_active, speed_boost_end_time, shield_active, player_speed, lives
    for prop in prop_list[:]:
        prop_rect = pygame.Rect(prop[0], prop[1], prop_radius*2, prop_radius*2)
        if check_collision(player_rect, prop_rect):
            # 加速道具
            if prop[2] == "speed":
                speed_boost_active = True
                speed_boost_end_time = time.time() + 5
                player_speed = original_speed * 2
            # 护盾道具
            elif prop[2] == "shield":
                shield_active = True
            # 生命道具
            elif prop[2] == "life":
                if lives < max_lives:
                    lives += 1
            # 移除已拾取的道具
            prop_list.remove(prop)

def reset_game():
    """重置游戏场景（保留生命、金币、皮肤）"""
    global player_x, player_y, obstacle_list, prop_list, score
    global speed_boost_active, speed_boost_end_time, shield_active, player_speed
    player_x = WIDTH // 2 - player_width // 2
    player_y = HEIGHT - player_height - 20
    obstacle_list.clear()
    prop_list.clear()
    score = 0
    player_speed = original_speed
    speed_boost_active = False
    speed_boost_end_time = 0
    shield_active = False

def draw_shop():
    """绘制商城界面"""
    screen.fill(GRAY)
    # 商城标题
    title = font.render("皮肤&生命商城（按B返回）", True, BLACK)
    screen.blit(title, (200, 30))
    # 金币显示
    coin_text = font.render(f"当前金币: {coin}", True, YELLOW)
    screen.blit(coin_text, (50, 100))
    
    # 生命购买区
    life_title = font.render("生命购买（每条30金币）", True, ORANGE)
    screen.blit(life_title, (50, 160))
    life_info = font.render(f"当前生命: {lives} | 上限: {max_lives}", True, BLACK)
    screen.blit(life_info, (50, 200))
    if coin >= life_price and lives < max_lives:
        buy_life_text = font.render("按L购买生命", True, GREEN)
    elif lives >= max_lives:
        buy_life_text = font.render("生命已达上限", True, GRAY)
    else:
        buy_life_text = font.render("金币不足（需30）", True, RED)
    screen.blit(buy_life_text, (50, 240))
    
    # 皮肤购买区
    skin_title = font.render("皮肤商城", True, PURPLE)
    screen.blit(skin_title, (50, 300))
    y = 340
    for idx, skin in enumerate(skins):
        # 皮肤预览
        pygame.draw.rect(screen, skin["color"], (50, y, 40, 60))
        # 皮肤信息
        if skin["unlocked"]:
            info = f"{skin['name']} [已解锁]"
            if idx == current_skin:
                info += " ✦使用中✦"
        else:
            info = f"{skin['name']} - {skin['price']}金币"
        skin_text = font.render(info, True, BLACK)
        screen.blit(skin_text, (120, y+10))
        
        # 购买/使用按钮
        if not skin["unlocked"]:
            if coin >= skin["price"]:
                buy_text = font.render("按K购买", True, GREEN)
            else:
                buy_text = font.render("金币不足", True, RED)
            screen.blit(buy_text, (500, y+10))
        else:
            use_text = font.render("按U使用", True, BLUE)
            screen.blit(use_text, (500, y+10))
        y += 80
    
    # 游戏结束后额外提示
    if game_state == "gameover":
        continue_text = font.render("购买生命后按C继续游戏", True, RED)
        screen.blit(continue_text, (50, HEIGHT-80))
    
    pygame.display.update()

def handle_shop_input():
    """处理商城输入"""
    global coin, lives, current_skin, game_state
    keys = pygame.key.get_pressed()
    
    # 返回游戏
    if keys[pygame.K_b]:
        time.sleep(0.2)
        return "play"
    
    # 购买生命
    if keys[pygame.K_l]:
        if coin >= life_price and lives < max_lives:
            coin -= life_price
            lives += 1
            time.sleep(0.2)
            # 购买生命后自动退出游戏结束状态
            if game_state == "gameover":
                game_state = "play"
                reset_game()
    
    # 皮肤操作
    for idx, skin in enumerate(skins):
        # 购买皮肤
        if not skin["unlocked"] and keys[pygame.K_k]:
            if coin >= skin["price"]:
                coin -= skin["price"]
                skins[idx]["unlocked"] = True
                time.sleep(0.2)
        # 使用皮肤
        if skin["unlocked"] and keys[pygame.K_u]:
            current_skin = idx
            time.sleep(0.2)
    
    # 游戏结束后继续游戏（需有生命）
    if game_state == "gameover" and keys[pygame.K_c] and lives > 0:
        game_state = "play"
        reset_game()
        time.sleep(0.2)
    
    return game_state

def handle_game_over():
    """处理游戏结束（生命为0）"""
    global game_state
    game_state = "gameover"
    # 直接跳转到商城
    while game_state == "gameover":
        draw_shop()
        game_state = handle_shop_input()
        # 处理退出事件
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

# ====================== 主游戏循环 ======================
def main():
    global score, player_x, player_y, player_speed, lives
    global speed_boost_active, speed_boost_end_time, shield_active, coin, game_state
    frame_count = 0
    
    while True:
        # 控制帧率
        clock.tick(60)
        frame_count += 1
        
        # 事件处理（全局）
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            # 切换到商城
            if event.type == pygame.KEYDOWN and event.key == pygame.K_s:
                game_state = "shop"
        
        # 商城状态
        if game_state == "shop" or game_state == "gameover":
            draw_shop()
            game_state = handle_shop_input()
            continue
        
        # 游戏中状态
        screen.fill(GRAY)
        
        # 加速道具过期检测
        if speed_boost_active and time.time() > speed_boost_end_time:
            speed_boost_active = False
            player_speed = original_speed
        
        # 玩家移动控制
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT] and player_x > 0:
            player_x -= player_speed
        if keys[pygame.K_RIGHT] and player_x < WIDTH - player_width:
            player_x += player_speed
        
        # 生成障碍物
        if frame_count % obstacle_spawn_rate == 0:
            obstacle_x = random.randint(0, WIDTH - obstacle_width)
            obstacle_list.append([obstacle_x, -obstacle_height])
        
        # 生成道具
        if frame_count % prop_spawn_rate == 0:
            prop_x = random.randint(0, WIDTH - prop_radius*2)
            prop_type = random.choice(PROP_TYPES)
            prop_list.append([prop_x, -prop_radius*2, prop_type])
        
        # 更新障碍物位置
        for obstacle in obstacle_list[:]:
            obstacle[1] += obstacle_speed
            # 移除超出屏幕的障碍物，加分和金币
            if obstacle[1] > HEIGHT:
                obstacle_list.remove(obstacle)
                score += 1
                coin += coin_per_score
        
        # 更新道具位置
        for prop in prop_list[:]:
            prop[1] += prop_speed
            # 移除超出屏幕的道具
            if prop[1] > HEIGHT:
                prop_list.remove(prop)
        
        # 创建玩家碰撞矩形
        player_rect = pygame.Rect(player_x, player_y, player_width, player_height)
        
        # 处理道具拾取
        handle_prop_pickup(player_rect)
        
        # 障碍物碰撞检测
        collision_detected = False
        for obstacle in obstacle_list:
            obstacle_rect = pygame.Rect(obstacle[0], obstacle[1], obstacle_width, obstacle_height)
            if check_collision(player_rect, obstacle_rect):
                collision_detected = True
                break
        
        # 碰撞处理
        if collision_detected:
            if shield_active:
                # 护盾抵消碰撞
                shield_active = False
                # 移除碰撞的障碍物
                for obstacle in obstacle_list[:]:
                    obstacle_rect = pygame.Rect(obstacle[0], obstacle[1], obstacle_width, obstacle_height)
                    if check_collision(player_rect, obstacle_rect):
                        obstacle_list.remove(obstacle)
            else:
                # 扣生命
                lives -= 1
                reset_game()
                # 生命为0则进入游戏结束（跳商城）
                if lives <= 0:
                    handle_game_over()
        
        # 绘制所有元素
        draw_player(player_x, player_y)
        for obstacle in obstacle_list:
            draw_obstacle(obstacle[0], obstacle[1])
        for prop in prop_list:
            draw_prop(prop[0], prop[1], prop[2])
        draw_game_ui()
        
        # 更新屏幕
        pygame.display.update()

if __name__ == "__main__":
    main()