import pygame
import random
import sys

# 初始化
pygame.init()
pygame.font.init()

# 窗口
WIDTH, HEIGHT = 480, 720
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("极速赛车｜道具版 高难度")
clock = pygame.time.Clock()
FPS = 60

# 配色
GRASS_GREEN  = (34, 139, 34)
ROAD_GRAY    = (55, 55, 55)
LINE_WHITE   = (235, 235, 235)
PLAYER_CAR   = (0, 150, 255)
ENEMY_CAR    = (220, 30, 30)
SCORE_GOLD   = (255, 215, 0)
TEXT_WHITE   = (255, 255, 255)
SHIELD_COLOR = (30, 200, 255)
SLOW_COLOR   = (80, 200, 80)
SPEED_COLOR  = (255, 120, 0)

# 车道
LANE_X = [110, 240, 370]

# 文字绘制
def draw_text(text, size, x, y, color=TEXT_WHITE):
    try:
        font = pygame.font.SysFont("Microsoft YaHei", size)
    except:
        font = pygame.font.Font(None, size)
    txt = font.render(text, True, color)
    rect = txt.get_rect(center=(x, y))
    screen.blit(txt, rect)

# 玩家赛车
class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.w, self.h = 40, 85
        self.image = pygame.Surface((self.w, self.h), pygame.SRCALPHA)
        self.image.fill(PLAYER_CAR)
        self.rect = self.image.get_rect()
        self.rect.centerx = LANE_X[1]
        self.rect.bottom = HEIGHT - 40
        self.move_speed = 9
        self.shield_time = 0
        self.speed_time = 0

    def update(self):
        key = pygame.key.get_pressed()
        spd = self.move_speed
        if self.speed_time > 0:
            spd *= 1.6
        if key[pygame.K_LEFT] and self.rect.left > 75:
            self.rect.x -= spd
        if key[pygame.K_RIGHT] and self.rect.right < 405:
            self.rect.x += spd
        
        if self.shield_time > 0:
            self.shield_time -= 1
        if self.speed_time > 0:
            self.speed_time -= 1

# 敌方赛车
class EnemyCar(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.w, self.h = 40, 85
        self.image = pygame.Surface((self.w, self.h))
        self.image.fill(ENEMY_CAR)
        self.rect = self.image.get_rect()
        self.rect.centerx = random.choice(LANE_X)
        self.rect.y = random.randint(-300, -100)
        self.base_speed = 7

    def update(self):
        self.rect.y += self.base_speed * slow_ratio
        if self.rect.top > HEIGHT:
            self.rect.centerx = random.choice(LANE_X)
            self.rect.y = random.randint(-300, -100)

# 道具类
class Item(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.type_list = ["shield","speed","slow"]
        self.type = random.choice(self.type_list)
        self.image = pygame.Surface((35,35))
        if self.type == "shield":
            self.image.fill(SHIELD_COLOR)
        elif self.type == "speed":
            self.image.fill(SPEED_COLOR)
        else:
            self.image.fill(SLOW_COLOR)
        self.rect = self.image.get_rect()
        self.rect.centerx = random.choice(LANE_X)
        self.rect.y = random.randint(-400,-100)
        self.speed = 5

    def update(self):
        self.rect.y += self.speed
        if self.rect.top > HEIGHT:
            self.kill()

# 开始界面
def start_page():
    while True:
        screen.fill(GRASS_GREEN)
        draw_text("🏁 极速赛车 🏁", 55, WIDTH//2, 160)
        draw_text("← → 左右躲避", 32, WIDTH//2, 280)
        draw_text("蓝色护盾｜橙色加速｜绿色减速", 26, WIDTH//2, 340)
        draw_text("难度超高，收集道具闯关", 28, WIDTH//2, 400)
        draw_text("按任意键开始", 30, WIDTH//2, 520)
        pygame.display.update()
        for e in pygame.event.get():
            if e.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if e.type == pygame.KEYDOWN:
                return
        clock.tick(FPS)

# 结束界面
def game_over_page(score):
    while True:
        screen.fill((15,15,15))
        draw_text("比赛结束", 65, WIDTH//2, 180, ENEMY_CAR)
        draw_text(f"最终得分：{score}", 38, WIDTH//2, 320, SCORE_GOLD)
        draw_text("按任意键重新挑战", 30, WIDTH//2, 460)
        pygame.display.update()
        for e in pygame.event.get():
            if e.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if e.type == pygame.KEYDOWN:
                return
        clock.tick(FPS)

# 主游戏
def game_run():
    global slow_ratio
    score = 0
    base_speed = 7
    max_speed = 18
    line_y = 0
    slow_ratio = 1.0
    slow_timer = 0

    all_group = pygame.sprite.Group()
    enemy_group = pygame.sprite.Group()
    item_group = pygame.sprite.Group()

    player = Player()
    all_group.add(player)

    for _ in range(4):
        car = EnemyCar()
        enemy_group.add(car)
        all_group.add(car)

    over = False
    item_spawn_timer = 0

    while True:
        clock.tick(FPS)
        for e in pygame.event.get():
            if e.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

        if slow_timer > 0:
            slow_timer -= 1
            slow_ratio = 0.4
        else:
            slow_ratio = 1.0

        if not over:
            now_speed = min(base_speed + score * 0.15, max_speed)
            for car in enemy_group:
                car.base_speed = now_speed

            all_group.update()

            item_spawn_timer += 1
            if item_spawn_timer >= 90:
                item = Item()
                item_group.add(item)
                all_group.add(item)
                item_spawn_timer = 0

            hit = pygame.sprite.spritecollide(player, enemy_group, False)
            if hit and player.shield_time <= 0:
                over = True

            item_hit = pygame.sprite.spritecollide(player, item_group, True)
            for it in item_hit:
                if it.type == "shield":
                    player.shield_time = 300
                elif it.type == "speed":
                    player.speed_time = 240
                    score += 5
                elif it.type == "slow":
                    slow_timer = 360

            for car in enemy_group:
                if car.rect.top > HEIGHT:
                    score += 1

        screen.fill(GRASS_GREEN)
        pygame.draw.rect(screen, ROAD_GRAY, (60, 0, 360, HEIGHT))

        # 修复：line_y 强制使用整数，彻底解决报错
        line_y = int(line_y + now_speed * slow_ratio if not over else 6)
        if line_y > 50:
            line_y = 0
            
        for y in range(line_y, HEIGHT, 50):
            pygame.draw.rect(screen, LINE_WHITE, (175, y, 6, 30))
            pygame.draw.rect(screen, LINE_WHITE, (295, y, 6, 30))

        all_group.draw(screen)

        if player.shield_time > 0:
            pygame.draw.ellipse(screen, SHIELD_COLOR,
                (player.rect.x-5, player.rect.y-5, player.w+10, player.h+10),3)

        draw_text(f"得分：{score}", 26, 75, 28, SCORE_GOLD)
        draw_text(f"速度：{round(now_speed,1)}", 22, 400, 28)
        if player.shield_time > 0:
            draw_text("护盾生效",22,WIDTH//2,28,SHIELD_COLOR)
        if slow_timer > 0:
            draw_text("全场减速",22,WIDTH//2,55,SLOW_COLOR)

        if over:
            draw_text("撞击失败！", 60, WIDTH//2, HEIGHT//2, ENEMY_CAR)

        pygame.display.update()
    return score

if __name__ == "__main__":
    while True:
        start_page()
        s = game_run()
        game_over_page(s)