import pygame
import random
import sys
import math

# 初始化
pygame.init()
WIDTH, HEIGHT = 720, 960
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("超强稳定赛车 | 左右移动 | Z射击 | 空格氮气")
clock = pygame.time.Clock()
FPS = 60

# 颜色（优化配色）
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY = (50, 50, 50)
ROAD = (30, 30, 30)
ROAD_LINE = (180, 180, 180)
PLAYER_PRIMARY = (0, 180, 255)
PLAYER_SECONDARY = (0, 120, 200)
ENEMY_PRIMARY = (255, 80, 80)
ENEMY_SECONDARY = (200, 40, 40)
BULLET = (255, 220, 0)
NITRO_COLOR = (255, 0, 255)
NITRO_TRAIL = (200, 100, 255)
SKY = (80, 120, 180)

# 车道
LANES = [WIDTH//2 - 180, WIDTH//2, WIDTH//2 + 180]
LANE_WIDTH = 180

# 玩家（优化图形）
class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        # 创建带圆角和渐变的赛车图形
        self.image = pygame.Surface((70, 120), pygame.SRCALPHA)
        self.image.fill((0, 0, 0, 0))  # 透明背景
        
        # 绘制赛车主体（圆角矩形）
        body_rect = pygame.Rect(5, 10, 60, 100)
        pygame.draw.rect(self.image, PLAYER_PRIMARY, body_rect, border_radius=15)
        pygame.draw.rect(self.image, PLAYER_SECONDARY, body_rect, 3, border_radius=15)
        
        # 绘制车窗
        window_rect = pygame.Rect(15, 20, 40, 40)
        pygame.draw.rect(self.image, (200, 220, 255, 180), window_rect, border_radius=8)
        
        # 绘制车轮
        wheel_radius = 10
        wheels = [
            (15, 95), (55, 95),  # 后轮
            (15, 25), (55, 25)   # 前轮
        ]
        for x, y in wheels:
            pygame.draw.circle(self.image, GRAY, (x, y), wheel_radius)
            pygame.draw.circle(self.image, BLACK, (x, y), wheel_radius - 2)
        
        self.rect = self.image.get_rect()
        self.rect.centerx = LANES[1]
        self.rect.bottom = HEIGHT - 50
        self.speed = 15
        self.nitro = 100
        self.is_nitro = False
        self.nitro_trail = []  # 氮气拖尾效果

    def update(self):
        keys = pygame.key.get_pressed()
        
        # 平滑移动（优化手感）
        if keys[pygame.K_LEFT] and self.rect.centerx > LANES[0]:
            self.rect.centerx = max(LANES[0], self.rect.centerx - self.speed)
        if keys[pygame.K_RIGHT] and self.rect.centerx < LANES[2]:
            self.rect.centerx = min(LANES[2], self.rect.centerx + self.speed)

        # 氮气加速
        if keys[pygame.K_SPACE] and self.nitro > 0:
            self.is_nitro = True
            self.nitro -= 1
            # 添加氮气拖尾效果
            self.nitro_trail.append([self.rect.centerx, self.rect.bottom + 10, 15])
        else:
            self.is_nitro = False
            if self.nitro < 100:
                self.nitro += 0.3
        
        # 更新氮气拖尾
        for i in range(len(self.nitro_trail)):
            self.nitro_trail[i][2] -= 0.5
            self.nitro_trail[i][1] += 8
        self.nitro_trail = [t for t in self.nitro_trail if t[2] > 0]

# 敌人（优化图形）
class Enemy(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface((70, 120), pygame.SRCALPHA)
        self.image.fill((0, 0, 0, 0))
        
        # 绘制敌人赛车
        body_rect = pygame.Rect(5, 10, 60, 100)
        pygame.draw.rect(self.image, ENEMY_PRIMARY, body_rect, border_radius=15)
        pygame.draw.rect(self.image, ENEMY_SECONDARY, body_rect, 3, border_radius=15)
        
        # 绘制车窗
        window_rect = pygame.Rect(15, 20, 40, 40)
        pygame.draw.rect(self.image, (255, 180, 180, 180), window_rect, border_radius=8)
        
        # 绘制车轮
        wheel_radius = 10
        wheels = [(15, 95), (55, 95), (15, 25), (55, 25)]
        for x, y in wheels:
            pygame.draw.circle(self.image, GRAY, (x, y), wheel_radius)
            pygame.draw.circle(self.image, BLACK, (x, y), wheel_radius - 2)
        
        self.rect = self.image.get_rect()
        self.rect.centerx = random.choice(LANES)
        self.rect.bottom = random.randint(-300, -50)
        self.speed = random.randint(8, 14)
        self.hit_flash = 0  # 被击中闪光效果

    def update(self):
        self.rect.y += self.speed
        if self.rect.top > HEIGHT:
            self.kill()
        
        # 更新击中闪光效果
        if self.hit_flash > 0:
            self.hit_flash -= 1

# 子弹（优化效果）
class Bullet(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.image = pygame.Surface((10, 20), pygame.SRCALPHA)
        # 绘制子弹（渐变效果）
        pygame.draw.ellipse(self.image, BULLET, (0, 0, 10, 20))
        pygame.draw.ellipse(self.image, (255, 255, 255), (2, 2, 6, 16))
        
        self.rect = self.image.get_rect()
        self.rect.centerx = x
        self.rect.bottom = y
        self.speed = -25
        self.trail = []  # 子弹轨迹

    def update(self):
        self.rect.y += self.speed
        # 添加子弹轨迹
        self.trail.append([self.rect.centerx, self.rect.centery, 5])
        for i in range(len(self.trail)):
            self.trail[i][2] -= 0.1
        self.trail = [t for t in self.trail if t[2] > 0]
        
        if self.rect.bottom < 0:
            self.kill()

# 氮气道具（优化图形）
class NitroItem(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface((40, 40), pygame.SRCALPHA)
        # 绘制氮气道具（星形）
        points = []
        for i in range(8):
            angle = math.radians(i * 45)
            radius = 20 if i % 2 == 0 else 10
            x = 20 + math.cos(angle) * radius
            y = 20 + math.sin(angle) * radius
            points.append((x, y))
        pygame.draw.polygon(self.image, NITRO_COLOR, points)
        pygame.draw.polygon(self.image, WHITE, points, 2)
        
        self.rect = self.image.get_rect()
        self.rect.centerx = random.choice(LANES)
        self.rect.bottom = random.randint(-800, -200)
        self.speed = 8
        self.rotation = 0  # 旋转效果

    def update(self):
        self.rect.y += self.speed
        self.rotation += 5
        self.image = pygame.transform.rotate(self.image, self.rotation)
        self.rect = self.image.get_rect(center=self.rect.center)
        
        if self.rect.top > HEIGHT:
            self.kill()

# 爆炸效果
class Explosion(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.frames = []
        # 创建爆炸帧
        for size in range(20, 80, 10):
            surf = pygame.Surface((size*2, size*2), pygame.SRCALPHA)
            pygame.draw.circle(surf, (255, 200, 0, 200), (size, size), size)
            pygame.draw.circle(surf, (255, 80, 0, 150), (size, size), size*0.7)
            pygame.draw.circle(surf, (200, 0, 0, 100), (size, size), size*0.4)
            self.frames.append(surf)
        
        self.current_frame = 0
        self.image = self.frames[self.current_frame]
        self.rect = self.image.get_rect(center=(x, y))
        self.frame_timer = 0

    def update(self):
        self.frame_timer += 1
        if self.frame_timer >= 3:
            self.current_frame += 1
            self.frame_timer = 0
            if self.current_frame >= len(self.frames):
                self.kill()
            else:
                self.image = self.frames[self.current_frame]

# 优化的道路绘制
def draw_road(scroll):
    # 绘制天空背景
    screen.fill(SKY)
    
    # 绘制道路（带边缘）
    road_rect = pygame.Rect(WIDTH//2 - 270, 0, 540, HEIGHT)
    pygame.draw.rect(screen, ROAD, road_rect)
    # 道路边缘线
    pygame.draw.rect(screen, WHITE, road_rect, 4)
    
    # 绘制车道分隔线
    for lane in LANES[:-1]:
        pygame.draw.line(screen, ROAD_LINE, (lane + LANE_WIDTH//2, 0), 
                         (lane + LANE_WIDTH//2, HEIGHT), 4)
    
    # 绘制道路中心线（移动的虚线）
    for y in range(int(scroll) % 80 - 80, HEIGHT, 80):
        pygame.draw.rect(screen, WHITE, (WIDTH//2 - 4, y, 8, 40))
    
    # 绘制路边护栏
    for x in [WIDTH//2 - 270, WIDTH//2 + 270]:
        for y in range(0, HEIGHT, 60):
            pygame.draw.rect(screen, GRAY, (x - 10, y, 10, 40))

# 绘制UI元素
def draw_ui(player, score, game_over):
    font = pygame.font.Font(None, 60)
    small_font = pygame.font.Font(None, 40)
    
    # 分数显示（带背景）
    score_bg = pygame.Rect(10, 10, 220, 70)
    pygame.draw.rect(screen, (0, 0, 0, 180), score_bg, border_radius=10)
    score_text = font.render(f"分数: {int(score)}", True, WHITE)
    screen.blit(score_text, (20, 20))
    
    # 氮气条（可视化进度条）
    nitro_bg = pygame.Rect(10, 90, 200, 30)
    pygame.draw.rect(screen, (0, 0, 0, 180), nitro_bg, border_radius=5)
    nitro_fill = pygame.Rect(12, 92, int(player.nitro * 2), 26)
    pygame.draw.rect(screen, NITRO_COLOR, nitro_fill, border_radius=3)
    nitro_text = small_font.render(f"氮气", True, WHITE)
    screen.blit(nitro_text, (220, 90))
    
    # 游戏结束界面
    if game_over:
        overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 180))
        screen.blit(overlay, (0, 0))
        
        go_font = pygame.font.Font(None, 80)
        go_text = go_font.render("GAME OVER", True, (255, 0, 0))
        restart_text = small_font.render("按任意键重来", True, WHITE)
        
        screen.blit(go_text, (WIDTH//2 - go_text.get_width()//2, HEIGHT//2 - 50))
        screen.blit(restart_text, (WIDTH//2 - restart_text.get_width()//2, HEIGHT//2 + 30))

# 绘制特效
def draw_effects(player, bullets, explosions):
    # 绘制氮气拖尾
    for trail in player.nitro_trail:
        x, y, alpha = trail
        surf = pygame.Surface((30, alpha * 4), pygame.SRCALPHA)
        pygame.draw.ellipse(surf, (*NITRO_TRAIL, alpha * 10), (0, 0, 30, alpha * 4))
        screen.blit(surf, (x - 15, y))
    
    # 绘制子弹轨迹
    for bullet in bullets:
        for trail in bullet.trail:
            x, y, alpha = trail
            pygame.draw.circle(screen, (*BULLET, alpha * 20), (int(x), int(y)), int(alpha))
    
    # 绘制爆炸效果
    explosions.draw(screen)
    
    # 绘制敌人击中闪光
    for enemy in [e for e in pygame.sprite.Group().sprites() if hasattr(e, 'hit_flash')]:
        if enemy.hit_flash > 0:
            flash_surf = pygame.Surface(enemy.rect.size, pygame.SRCALPHA)
            flash_surf.fill((255, 255, 255, 150))
            screen.blit(flash_surf, enemy.rect)

# 主游戏
def main():
    player = Player()
    all_sprites = pygame.sprite.Group()
    enemies = pygame.sprite.Group()
    bullets = pygame.sprite.Group()
    items = pygame.sprite.Group()
    explosions = pygame.sprite.Group()
    
    all_sprites.add(player)

    scroll = 0
    spawn_timer = 0
    item_spawn_timer = 0
    game_over = False
    score = 0

    while True:
        clock.tick(FPS)
        
        # 氮气影响速度
        base_scroll = 18 if player.is_nitro else 12
        scroll += base_scroll

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if game_over:
                    # 重新开始游戏
                    main()
                if event.key == pygame.K_z and not game_over:
                    bullet = Bullet(player.rect.centerx, player.rect.top)
                    all_sprites.add(bullet)
                    bullets.add(bullet)

        if not game_over:
            all_sprites.update()
            explosions.update()

            # 敌人生成
            spawn_timer += 1
            if spawn_timer > random.randint(20, 40):
                enemy = Enemy()
                all_sprites.add(enemy)
                enemies.add(enemy)
                spawn_timer = 0

            # 道具生成
            item_spawn_timer += 1
            if item_spawn_timer > 300:
                item = NitroItem()
                all_sprites.add(item)
                items.add(item)
                item_spawn_timer = 0

            # 子弹打敌人
            hits = pygame.sprite.groupcollide(enemies, bullets, True, True)
            for hit in hits:
                score += 50
                hit.hit_flash = 5
                # 添加爆炸效果
                explosion = Explosion(hit.rect.centerx, hit.rect.centery)
                explosions.add(explosion)

            # 吃氮气
            item_hits = pygame.sprite.spritecollide(player, items, True)
            for i in item_hits:
                player.nitro = min(100, player.nitro + 40)
                score += 30

            # 撞车
            collisions = pygame.sprite.spritecollideany(player, enemies)
            if collisions:
                # 添加撞车爆炸
                explosion = Explosion(player.rect.centerx, player.rect.centery)
                explosions.add(explosion)
                game_over = True

        # 绘制游戏元素
        draw_road(scroll)
        all_sprites.draw(screen)
        draw_effects(player, bullets, explosions)
        draw_ui(player, score, game_over)

        pygame.display.flip()

if __name__ == "__main__":
    main()