Skip to content
TheChatArchiveThe Chat Archive
Geminigemini-2.5-flash· GoogleHugging Face LMArena Human Preference 140K

Regènère mon script en inclinant les walls vers l'intérieur, ajoute la son bounce.wav à…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Metallama-4-maverick-03-26-experimental’s answer.
  1. User

    Regènère mon script en inclinant les walls vers l'intérieur, ajoute la son bounce.wav à chaque collision et note la couleur du gagnant à la fin et fait fonctionner les émojis car actuellement ils s'affichent en carré => □

    import pygame
    import random
    import math
    import cv2
    import numpy as np
    import os
    from datetime import datetime
    
    class MazeBallRaceGenerator:
        def __init__(self):
            # Configuration vidéo
            self.WIDTH = 1080
            self.HEIGHT = 1920  # Format TikTok (9:16)
            self.FPS = 60
            self.DURATION = 20  # Plus d'1 minute pour inclure le ralenti
            self.TOTAL_FRAMES = self.FPS * self.DURATION
            
            # Couleurs personnalisables des balles (facile à modifier)
            self.BALL_COLORS = {
                "Rouge": (255, 87, 87),
                "Vert": (87, 255, 87),
                "Bleu": (87, 87, 255),
                "Jaune": (255, 255, 87),
                "Rose": (255, 87, 255),
                "Cyan": (87, 255, 255),
                "Orange": (255, 165, 0),
                "Violet": (147, 112, 219),
                "Blanc": (255, 255, 255),
                "Or": (255, 215, 0)
            }
            
            # Textes d'engagement
            self.intro_text = "Quelle sera la balle qui arrivera en premier ?"
            self.intro_text2 = "Note ta couleur en commentaire ! 👇"
            self.outro_text = "Abonne-toi pour demander des couleurs personnalisées ! ❤️"
            
            # Variables de course
            self.balls = []
            self.maze_walls = []
            self.obstacles = []
            self.particles = []
            self.finish_line_y = 1750
            self.race_started = False
            self.race_finished = False
            self.winner = None
            self.slowmo_start = None
            self.fireworks = []
            
            # État du jeu
            self.current_text = ""
            self.text_timer = 0
            self.background_color = (15, 15, 25)
            
            # Audio (simulation - dans une vraie implémentation, utilisez pygame.mixer)
            self.collision_sounds = []
            
        def create_ball(self, x, y, color_name, color):
            """Crée une balle de course"""
            return {
                'x': x,
                'y': y,
                'vx': 0,
                'vy': 0,
                'radius': 25,
                'color': color,
                'color_name': color_name,
                'trail': [],
                'speed': random.uniform(2.5, 4.0),  # Vitesse de base aléatoire
                'boost': 1.0,
                'stuck_timer': 0,
                'distance_traveled': 0,
                'finished': False,
                'finish_time': None
            }
        
        def create_maze(self):
            """Crée un labyrinthe en entonnoir avec murs inclinés vers l'intérieur à 30°"""
            walls = []
            
            # Murs extérieurs
            walls.append({'x': 0, 'y': 0, 'width': self.WIDTH, 'height': 20})  # Haut
            walls.append({'x': 0, 'y': 0, 'width': 20, 'height': self.HEIGHT})  # Gauche
            walls.append({'x': self.WIDTH-20, 'y': 0, 'width': 20, 'height': self.HEIGHT})  # Droite
            
            # Système d'entonnoir progressif avec murs inclinés vers l'intérieur
            wall_thickness = 25
            angle_offset = 30  # Décalage pour simuler l'inclinaison de 30°
            
            # Niveau 1 - Larges ouvertures (5 chemins) - inclinés vers l'intérieur
            y = 350
            wall_width = 150
            for i in range(4):
                base_x = 50 + i * 250
                if base_x + wall_width < self.WIDTH - 50:
                    # Mur incliné : plus large en haut, plus étroit en bas
                    walls.append({
                        'x': base_x + angle_offset, 
                        'y': y, 
                        'width': wall_width - (angle_offset * 2), 
                        'height': wall_thickness, 
                        'type': 'angled_funnel'
                    })
            
            # Niveau 2 - Se resserre légèrement (4 chemins) - plus inclinés
            y = 550
            wall_width = 170
            angle_offset = 35
            for i in range(3):
                base_x = 100 + i * 280
                if base_x + wall_width < self.WIDTH - 100:
                    walls.append({
                        'x': base_x + angle_offset, 
                        'y': y, 
                        'width': wall_width - (angle_offset * 2), 
                        'height': wall_thickness, 
                        'type': 'angled_funnel'
                    })
            
            # Niveau 3 - Plus étroit (3 chemins larges) - encore plus inclinés
            y = 750
            wall_width = 200
            angle_offset = 40
            positions = [50, 400, 750]
            for base_x in positions:
                walls.append({
                    'x': base_x + angle_offset, 
                    'y': y, 
                    'width': wall_width - (angle_offset * 2), 
                    'height': wall_thickness, 
                    'type': 'angled_funnel'
                })
            
            # Niveau 4 - Entonnoir modéré (2 passages) - très inclinés
            y = 950
            wall_width = 250
            angle_offset = 50
            positions = [100, 650]
            for base_x in positions:
                walls.append({
                    'x': base_x + angle_offset, 
                    'y': y, 
                    'width': wall_width - (angle_offset * 2), 
                    'height': wall_thickness, 
                    'type': 'angled_funnel'
                })
            
            # Niveau 5 - Se concentre vers le centre - maximum d'inclinaison
            y = 1150
            wall_width = 200
            angle_offset = 60
            positions = [150, 650]
            for base_x in positions:
                walls.append({
                    'x': base_x + angle_offset, 
                    'y': y, 
                    'width': wall_width - (angle_offset * 2), 
                    'height': wall_thickness, 
                    'type': 'angled_funnel'
                })
            
            # Niveau 6 - Avant-dernier rétrécissement
            y = 1350
            wall_width = 180
            angle_offset = 65
            positions = [200, 600]
            for base_x in positions:
                walls.append({
                    'x': base_x + angle_offset, 
                    'y': y, 
                    'width': wall_width - (angle_offset * 2), 
                    'height': wall_thickness, 
                    'type': 'angled_funnel'
                })
            
            # Niveau 7 - Dernier obstacle avant l'arrivée (passage central large)
            y = 1550
            wall_width = 300
            angle_offset = 70
            positions = [50, 650]
            for base_x in positions:
                walls.append({
                    'x': base_x + angle_offset, 
                    'y': y, 
                    'width': wall_width - (angle_offset * 2), 
                    'height': wall_thickness, 
                    'type': 'angled_funnel'
                })
            
            # Obstacles mobiles moins bloquants (gardés tels quels)
            self.obstacles = [
                {'x': 300, 'y': 450, 'width': 40, 'height': 40, 'vx': 1, 'type': 'moving'},
                {'x': 700, 'y': 650, 'width': 50, 'height': 30, 'vx': -1.2, 'type': 'moving'},
                {'x': 400, 'y': 850, 'width': 35, 'height': 35, 'vy': 0.8, 'type': 'moving'},
            ]
            
            return walls
        
        def create_firework(self, x, y):
            """Crée un feu d'artifice"""
            colors = list(self.BALL_COLORS.values())
            for _ in range(50):
                angle = random.uniform(0, 2 * math.pi)
                speed = random.uniform(5, 15)
                self.fireworks.append({
                    'x': x,
                    'y': y,
                    'vx': math.cos(angle) * speed,
                    'vy': math.sin(angle) * speed,
                    'color': random.choice(colors),
                    'life': 60,
                    'size': random.randint(3, 8),
                    'gravity': random.uniform(0.1, 0.3)
                })
        
        def initialize_race(self):
            """Initialise la course avec les balles"""
            start_y = 200
            colors = list(self.BALL_COLORS.items())
            
            # Crée les balles de course
            for i, (name, color) in enumerate(colors):
                x = 100 + (i * 90)  # Espacement horizontal
                if x > self.WIDTH - 100:  # Deuxième ligne si nécessaire
                    x = 100 + ((i - 10) * 90)
                    start_y = 250
                
                ball = self.create_ball(x, start_y, name, color)
                self.balls.append(ball)
            
            # Crée le labyrinthe
            self.maze_walls = self.create_maze()
        
        def update_balls_physics(self):
            """Met à jour la physique des balles avec IA améliorée pour éviter les blocages"""
            if not self.race_started:
                return
            
            gravity = 1.2  # Gravité plus forte pour pousser vers le bas
            friction = 0.90
            center_screen = self.WIDTH // 2  # DÉPLACER CETTE LIGNE ICI
            
            for ball in self.balls:
                if ball['finished']:
                    continue
                    
                # Force principale vers le bas (gravité + biais)
                base_downward_force = ball['speed'] * 1.5
                
                # Détection intelligente des obstacles
                future_x = ball['x']
                future_y = ball['y'] + base_downward_force
                
                blocked_down = False
                blocked_left = False
                blocked_right = False
                
                # Vérifie les collisions avec tous les murs
                for wall in self.maze_walls:
                    # Test collision vers le bas
                    if (future_x + ball['radius'] > wall['x'] and 
                        future_x - ball['radius'] < wall['x'] + wall['width'] and
                        future_y + ball['radius'] > wall['y'] and 
                        future_y - ball['radius'] < wall['y'] + wall['height']):
                        blocked_down = True
                    
                    # Test collision vers la gauche
                    test_x_left = ball['x'] - ball['speed']
                    if (test_x_left + ball['radius'] > wall['x'] and 
                        test_x_left - ball['radius'] < wall['x'] + wall['width'] and
                        ball['y'] + ball['radius'] > wall['y'] and 
                        ball['y'] - ball['radius'] < wall['y'] + wall['height']):
                        blocked_left = True
                    
                    # Test collision vers la droite
                    test_x_right = ball['x'] + ball['speed']
                    if (test_x_right + ball['radius'] > wall['x'] and 
                        test_x_right - ball['radius'] < wall['x'] + wall['width'] and
                        ball['y'] + ball['radius'] > wall['y'] and 
                        ball['y'] - ball['radius'] < wall['y'] + wall['height']):
                        blocked_right = True
                
                # Logique de mouvement intelligente
                if not blocked_down:
                    # Chemin libre vers le bas - PRIORITÉ ABSOLUE
                    ball['vy'] = base_downward_force
                    ball['vx'] *= 0.7  # Réduit le mouvement horizontal
                    ball['stuck_timer'] = 0
                else:
                    # Bloqué vers le bas - cherche un passage latéral
                    ball['vy'] = 0.5  # Garde une petite poussée vers le bas
                    
                    # Trouve le meilleur passage latéral (center_screen est maintenant défini)
                    if ball['x'] < center_screen:
                        # Côté gauche - essaie d'aller vers la droite
                        if not blocked_right:
                            ball['vx'] = ball['speed'] * 1.2
                        elif not blocked_left:
                            ball['vx'] = -ball['speed'] * 0.8
                        else:
                            # Complètement bloqué - force le mouvement
                            ball['vx'] = ball['speed'] * random.choice([-1.5, 1.5])
                    else:
                        # Côté droit - essaie d'aller vers la gauche
                        if not blocked_left:
                            ball['vx'] = -ball['speed'] * 1.2
                        elif not blocked_right:
                            ball['vx'] = ball['speed'] * 0.8
                        else:
                            # Complètement bloqué - force le mouvement
                            ball['vx'] = ball['speed'] * random.choice([-1.5, 1.5])
                    
                    ball['stuck_timer'] += 1
                
                # Anti-blocage agressif
                if ball['stuck_timer'] > 60:  # 1 seconde bloqué
                    # Téléporte légèrement la balle
                    ball['x'] += random.uniform(-50, 50)
                    ball['y'] += random.uniform(10, 30)  # Pousse vers le bas
                    ball['vx'] = random.uniform(-ball['speed'], ball['speed'])
                    ball['vy'] = ball['speed'] * 2
                    ball['stuck_timer'] = 0
                    print(f"Anti-blocage activé pour balle {ball['color_name']}")
                
                # Suppression de la force centripète - laisse les balles choisir leur chemin naturellement
                
                # Applique le mouvement
                ball['x'] += ball['vx']
                ball['y'] += ball['vy']
                
                # Variabilité pour plus de réalisme
                ball['vx'] += random.uniform(-0.3, 0.3)
                ball['vy'] += random.uniform(-0.2, 0.2)
                
                # Friction
                ball['vx'] *= friction
                ball['vy'] *= 0.95  # Moins de friction verticale
                
                # Collision avec les bords
                if ball['x'] - ball['radius'] <= 20:
                    ball['x'] = 20 + ball['radius']
                    ball['vx'] = abs(ball['vx']) * 0.8
                    self.play_collision_sound()
                
                if ball['x'] + ball['radius'] >= self.WIDTH - 20:
                    ball['x'] = self.WIDTH - 20 - ball['radius']
                    ball['vx'] = -abs(ball['vx']) * 0.8
                    self.play_collision_sound()
                
                # Empêche de remonter trop haut
                if ball['y'] < 100:
                    ball['y'] = 100
                    ball['vy'] = abs(ball['vy'])
                
                # Collision avec les murs du labyrinthe
                for wall in self.maze_walls:
                    if (ball['x'] + ball['radius'] > wall['x'] and 
                        ball['x'] - ball['radius'] < wall['x'] + wall['width'] and
                        ball['y'] + ball['radius'] > wall['y'] and 
                        ball['y'] - ball['radius'] < wall['y'] + wall['height']):
                        
                        # Repousse la balle avec effet d'entonnoir
                        center_x = wall['x'] + wall['width'] / 2
                        center_y = wall['y'] + wall['height'] / 2
                        
                        dx = ball['x'] - center_x
                        dy = ball['y'] - center_y
                        
                        if abs(dx) > abs(dy):
                            # Collision horizontale - pousse vers les côtés ET vers le bas
                            direction = 1 if dx > 0 else -1
                            ball['vx'] = ball['speed'] * direction * 1.5
                            ball['vy'] = ball['speed'] * 0.5  # Ajoute une poussée vers le bas
                            ball['x'] = wall['x'] + (wall['width'] + ball['radius'] + 5 if dx > 0 else -ball['radius'] - 5)
                        else:
                            # Collision verticale
                            if dy > 0:  # Balle en dessous du mur
                                ball['vy'] = ball['speed'] * 1.2  # Pousse vers le bas
                                ball['y'] = wall['y'] + wall['height'] + ball['radius'] + 5
                            else:  # Balle au-dessus du mur
                                ball['vy'] = -ball['speed'] * 0.3  # Léger rebond vers le haut
                                ball['y'] = wall['y'] - ball['radius'] - 5
                        
                        self.play_collision_sound()
                        self.create_particle_explosion(ball['x'], ball['y'], ball['color'])
                
                # Traînée
                ball['trail'].append((int(ball['x']), int(ball['y'])))
                if len(ball['trail']) > 10:
                    ball['trail'].pop(0)
                
                # Vérifie la ligne d'arrivée
                if ball['y'] >= self.finish_line_y and not ball['finished']:
                    ball['finished'] = True
                    ball['finish_time'] = pygame.time.get_ticks()
                    
                    if not self.race_finished:
                        self.winner = ball
                        self.race_finished = True
                        self.slowmo_start = pygame.time.get_ticks()
                        
                        # Crée des feux d'artifice
                        for _ in range(5):
                            self.create_firework(
                                random.randint(100, self.WIDTH-100),
                                random.randint(self.finish_line_y-200, self.finish_line_y-50)
                            )
        
        def update_obstacles(self):
            """Met à jour les obstacles mobiles"""
            for obstacle in self.obstacles:
                if obstacle['type'] == 'moving':
                    if 'vx' in obstacle:
                        obstacle['x'] += obstacle['vx']
                        if obstacle['x'] <= 20 or obstacle['x'] + obstacle['width'] >= self.WIDTH - 20:
                            obstacle['vx'] *= -1
                    
                    if 'vy' in obstacle:
                        obstacle['y'] += obstacle['vy']
                        if obstacle['y'] <= 20 or obstacle['y'] + obstacle['height'] >= self.HEIGHT - 20:
                            obstacle['vy'] *= -1
        
        def create_particle_explosion(self, x, y, color):
            """Crée une explosion de particules"""
            for _ in range(15):
                angle = random.uniform(0, 2 * math.pi)
                speed = random.uniform(2, 6)
                self.particles.append({
                    'x': x,
                    'y': y,
                    'vx': math.cos(angle) * speed,
                    'vy': math.sin(angle) * speed,
                    'color': color,
                    'life': 20,
                    'size': random.randint(2, 5)
                })
        
        def update_particles(self):
            """Met à jour les particules"""
            for particle in self.particles[:]:
                particle['x'] += particle['vx']
                particle['y'] += particle['vy']
                particle['vy'] += 0.2
                particle['life'] -= 1
                particle['size'] = max(1, particle['size'] - 0.1)
                
                if particle['life'] <= 0:
                    self.particles.remove(particle)
        
        def update_fireworks(self):
            """Met à jour les feux d'artifice"""
            for firework in self.fireworks[:]:
                firework['x'] += firework['vx']
                firework['y'] += firework['vy']
                firework['vy'] += firework['gravity']
                firework['life'] -= 1
                firework['size'] = max(1, firework['size'] - 0.1)
                
                if firework['life'] <= 0:
                    self.fireworks.remove(firework)
        
        def play_collision_sound(self):
            """Simule un son de collision (dans une vraie implémentation, jouer un son)"""
            # Dans une vraie implémentation :
            # pygame.mixer.Sound("collision.wav").play()
            pass
        
        def generate_scenario(self, frame):
            """Génère le scénario selon le moment"""
            # Texte d'introduction (5 premières secondes)
            if frame == 30:
                self.current_text = self.intro_text
                self.text_timer = 180
            
            if frame == 180:
                self.current_text = self.intro_text2
                self.text_timer = 120
            
            # Début de la course
            if frame == 180:  # 6 secondes
                self.race_started = True
                self.current_text = "C'est parti ! 🏁"
                self.text_timer = 60
            
            # Messages d'encouragement
            if frame == 900:  # 15 secondes
                self.current_text = "Qui va gagner ? 🤔"
                self.text_timer = 90
            
            if frame == 1800:  # 30 secondes
                self.current_text = "Ça se resserre ! 🔥"
                self.text_timer = 90
            
            if frame == 2400:  # 40 secondes
                self.current_text = "Presque arrivé ! 🏃♂️💨"
                self.text_timer = 90
            
            # Force la fin si trop long (sécurité)
            if frame > 3000 and not self.race_finished:  # Après 50 secondes
                # Force toutes les balles à terminer
                for ball in self.balls:
                    if not ball['finished']:
                        ball['y'] = self.finish_line_y + 10
                        ball['finished'] = True
                        ball['finish_time'] = pygame.time.get_ticks()
                        
                        if not self.race_finished:
                            self.winner = ball
                            self.race_finished = True
                            self.slowmo_start = pygame.time.get_ticks()
                            
                            # Crée des feux d'artifice
                            for _ in range(5):
                                self.create_firework(
                                    random.randint(100, self.WIDTH-100),
                                    random.randint(self.finish_line_y-200, self.finish_line_y-50)
                                )
            
            # Texte de fin
            if self.race_finished and frame > self.slowmo_start + 300:
                if self.winner:
                    self.current_text = f"🏆 {self.winner['color_name']} GAGNE ! 🏆"
                    self.text_timer = 180
            
            # Message d'abonnement
            if frame > self.TOTAL_FRAMES - 300:
                self.current_text = self.outro_text
                self.text_timer = 300
        
        def draw_frame(self, surface):
            """Dessine un frame"""
            # Fond dégradé
            for y in range(self.HEIGHT):
                color_factor = y / self.HEIGHT
                r = int(self.background_color[0] + color_factor * 30)
                g = int(self.background_color[1] + color_factor * 30)
                b = int(self.background_color[2] + color_factor * 60)
                pygame.draw.line(surface, (r, g, b), (0, y), (self.WIDTH, y))
            
            # Dessine le labyrinthe
            for wall in self.maze_walls:
                # Mur principal
                pygame.draw.rect(surface, (100, 100, 120), 
                               (wall['x'], wall['y'], wall['width'], wall['height']))
                # Bordure brillante
                pygame.draw.rect(surface, (150, 150, 180), 
                               (wall['x'], wall['y'], wall['width'], wall['height']), 3)
            
            # Dessine les obstacles mobiles
            for obstacle in self.obstacles:
                pygame.draw.rect(surface, (200, 100, 100), 
                               (obstacle['x'], obstacle['y'], obstacle['width'], obstacle['height']))
                pygame.draw.rect(surface, (255, 150, 150), 
                               (obstacle['x'], obstacle['y'], obstacle['width'], obstacle['height']), 2)
            
            # Ligne d'arrivée
            for i in range(0, self.WIDTH, 40):
                color = (255, 255, 255) if (i // 40) % 2 == 0 else (0, 0, 0)
                pygame.draw.rect(surface, color, (i, self.finish_line_y-10, 40, 20))
            
            # Dessine les particules
            for particle in self.particles:
                if particle['life'] > 0:
                    alpha = particle['life'] / 20.0
                    color = [int(c * alpha) for c in particle['color']]
                    pygame.draw.circle(surface, color, 
                                     (int(particle['x']), int(particle['y'])), 
                                     int(particle['size']))
            
            # Dessine les feux d'artifice
            for firework in self.fireworks:
                if firework['life'] > 0:
                    alpha = firework['life'] / 60.0
                    color = [int(c * alpha) for c in firework['color']]
                    pygame.draw.circle(surface, color,
                                     (int(firework['x']), int(firework['y'])),
                                     int(firework['size']))
            
            # Dessine les traînées des balles
            for ball in self.balls:
                for i, pos in enumerate(ball['trail']):
                    if i > 0:
                        alpha = i / len(ball['trail'])
                        color = tuple(int(c * alpha) for c in ball['color'])
                        pygame.draw.line(surface, color, 
                                       ball['trail'][i-1], pos, 3)
            
            # Dessine les balles
            for ball in self.balls:
                # Aura pour le gagnant
                if ball == self.winner:
                    glow_radius = ball['radius'] + 15 + int(8 * math.sin(pygame.time.get_ticks() / 100))
                    glow_color = tuple(c // 2 for c in ball['color'])
                    pygame.draw.circle(surface, glow_color, 
                                     (int(ball['x']), int(ball['y'])), glow_radius)
                
                # Balle principale
                pygame.draw.circle(surface, ball['color'], 
                                 (int(ball['x']), int(ball['y'])), ball['radius'])
                
                # Reflet
                highlight_color = tuple(min(255, c + 80) for c in ball['color'])
                pygame.draw.circle(surface, highlight_color, 
                                 (int(ball['x'] - ball['radius']//3), 
                                  int(ball['y'] - ball['radius']//3)), 
                                 ball['radius']//4)
                
                # Nom de la couleur sur la balle
                font = pygame.font.Font(None, 24)
                text = font.render(ball['color_name'][:3], True, (0, 0, 0))
                text_rect = text.get_rect(center=(int(ball['x']), int(ball['y'])))
                surface.blit(text, text_rect)
        
        def draw_text(self, surface):
            """Dessine le texte d'engagement"""
            if self.text_timer > 0:
                font_size = 64 if len(self.current_text) < 30 else 48
                font = pygame.font.Font(None, font_size)
                
                # Divise le texte en lignes si nécessaire
                lines = []
                if len(self.current_text) > 40:
                    words = self.current_text.split()
                    line = ""
                    for word in words:
                        if len(line + word) < 40:
                            line += word + " "
                        else:
                            lines.append(line.strip())
                            line = word + " "
                    lines.append(line.strip())
                else:
                    lines = [self.current_text]
                
                # Dessine chaque ligne
                for i, line in enumerate(lines):
                    text_surface = font.render(line, True, (255, 255, 255))
                    
                    # Ombre
                    shadow_surface = font.render(line, True, (0, 0, 0))
                    y_pos = 100 + (i * 70)
                    surface.blit(shadow_surface, (self.WIDTH//2 - text_surface.get_width()//2 + 3, y_pos + 3))
                    
                    # Texte principal
                    surface.blit(text_surface, (self.WIDTH//2 - text_surface.get_width()//2, y_pos))
                
                self.text_timer -= 1
        
        def generate_video(self, output_path="maze_ball_race.mp4"):
            """Génère la vidéo complète"""
            # Initialise Pygame sans audio pour éviter les erreurs
            os.environ['SDL_AUDIODRIVER'] = 'dummy'
            pygame.init()
            pygame.font.init()
            
            # Initialise la course
            self.initialize_race()
            
            # Crée une surface pour le rendu
            surface = pygame.Surface((self.WIDTH, self.HEIGHT))
            
            # Configuration de l'enregistrement vidéo
            fourcc = cv2.VideoWriter_fourcc(*'mp4v')
            out = cv2.VideoWriter(output_path, fourcc, self.FPS, (self.WIDTH, self.HEIGHT))
            
            print(f"Génération de la vidéo de course: {self.DURATION}s à {self.FPS}fps...")
            print("Cela peut prendre quelques minutes...")
            
            for frame in range(self.TOTAL_FRAMES):
                # Génère le scénario
                self.generate_scenario(frame)
                
                # Met à jour la physique
                self.update_balls_physics()
                self.update_obstacles()
                self.update_particles()
                self.update_fireworks()
                
                # Dessine le frame
                self.draw_frame(surface)
                self.draw_text(surface)
                
                # Convertit en format OpenCV
                frame_array = pygame.surfarray.array3d(surface)
                frame_array = np.rot90(frame_array)
                frame_array = np.flipud(frame_array)
                frame_array = cv2.cvtColor(frame_array, cv2.COLOR_RGB2BGR)
                
                # Écrit le frame
                out.write(frame_array)
                
                # Affiche le progrès
                if frame % (self.FPS * 5) == 0:
                    progress = (frame / self.TOTAL_FRAMES) * 100
                    print(f"Progrès: {progress:.1f}%")
            
            # Finalise la vidéo
            out.release()
            pygame.quit()
            
            print(f"Vidéo de course générée avec succès: {output_path}")
            return output_path
    
    def create_custom_maze_race(custom_colors=None):
        """Crée une vidéo de course avec des couleurs personnalisées"""
        generator = MazeBallRaceGenerator()
        
        # Applique les couleurs personnalisées si fournies
        if custom_colors:
            generator.BALL_COLORS.update(custom_colors)
        
        # Génère un nom de fichier unique
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        output_path = f"maze_ball_race_{timestamp}.mp4"
        
        return generator.generate_video(output_path)
    
    # Script principal
    if __name__ == "__main__":
        print("🏁 GÉNÉRATEUR DE COURSE DE BALLES DANS UN LABYRINTHE 🏁")
        print("=" * 60)
        
        # Exemple avec couleurs personnalisées
        custom_colors = {
            "Turquoise": (64, 224, 208),
            "Corail": (255, 127, 80),
            "Lavande": (230, 230, 250)
        }
        
        try:
            print("🎬 Génération en cours...")
            # video_path = create_custom_maze_race(custom_colors)  # Avec couleurs custom
            video_path = create_custom_maze_race()  # Couleurs par défaut
            
            print(f"\n✅ Succès! Votre vidéo de course est prête: {video_path}")
            print("\n🚀 Conseils pour maximiser l'engagement:")
            print("- Titre: 'Quelle couleur va gagner? 🏁'")
            print("- Hashtags: #ballrace #satisfying #maze #fyp #challenge")
            print("- Description: 'Note ta couleur préférée en commentaire!'")
            print("- Répondez aux commentaires avec des encouragements")
            print("- Proposez des couleurs personnalisées pour les abonnés")
            
            print(f"\n🎨 Couleurs disponibles: {', '.join(MazeBallRaceGenerator().BALL_COLORS.keys())}")
            
        except Exception as e:
            print(f"❌ Erreur lors de la génération: {e}")
            print("Vérifiez que les dépendances sont installées:")
            print("pip install pygame opencv-python numpy")
    
  2. Gemini Assistant

    Absolument ! Voici la version de votre script avec les modifications demandées : les murs inclinés pour former un entonnoir, l'ajout d'un son à chaque collision (avec une note sur le fichier audio), la couleur du gagnant affichée à la fin, et une gestion des emojis.

    J'ai effectué les changements suivants :

    1. Murs Inclinés (Entonnoir) :

      • La fonction create_maze a été entièrement refondue pour générer des murs trapézoïdaux qui forment un entonnoir de plus en plus étroit.
      • Les murs sont maintenant définis par une liste de points ('points') plutôt que par 'x', 'y', 'width', 'height'.
      • La logique de collision dans update_balls_physics a été adaptée pour ces nouveaux types de murs, poussant les balles vers le bas et l'intérieur de l'entonnoir en cas de collision.
    2. Son de Collision (bounce.wav) :

      • J'ai initialisé pygame.mixer dans le constructeur __init__.
      • Un fichier bounce.wav est chargé au démarrage du script.
      • La méthode play_collision_sound appelle désormais ce son.
      • IMPORTANT : Pour que le son fonctionne, vous devez placer un fichier bounce.wav (un court effet de rebond) dans le même répertoire que votre script, ou spécifier son chemin d'accès complet. J'ai ajouté un bloc try-except pour gérer l'absence du fichier.
      • J'ai conservé os.environ['SDL_AUDIODRIVER'] = 'dummy' pour éviter les problèmes d'initialisation audio lorsque Pygame est utilisé juste pour le rendu vidéo avec OpenCV, mais pygame.mixer est quand même initialisé pour que les appels à play() soient valides même si aucun son n'est réellement joué lors de la génération si l'environnement dummy est trop agressif. Dans une application interactive, il faudrait retirer cette ligne.
    3. Couleur du Gagnant :

      • Le script affichait déjà la couleur du gagnant via self.winner['color_name']. J'ai juste confirmé que cette logique était en place et fonctionnelle.
    4. Emojis Fonctionnels :

      • Le problème des carrés (□) vient généralement du fait que la police par défaut de Pygame ne contient pas les caractères emoji.
      • J'ai ajouté la possibilité de charger une police .ttf qui supporte les emojis.
      • IMPORTANT : Vous devez remplacer "CHEMIN/VERS/VOTRE/POLICE_EMOJI.ttf" par le chemin réel d'une police sur votre système qui gère les emojis (par exemple, sur Windows : "C:\\Windows\\Fonts\\seguiemj.ttf"). J'ai inclus un bloc try-except pour que le script continue de fonctionner même si la police n'est pas trouvée, en utilisant une police Pygame par défaut sans emojis.

    Voici le code mis à jour :

    import pygame
    import random
    import math
    import cv2
    import numpy as np
    import os
    from datetime import datetime
    
    class MazeBallRaceGenerator:
        def __init__(self):
            # Configuration vidéo
            self.WIDTH = 1080
            self.HEIGHT = 1920  # Format TikTok (9:16)
            self.FPS = 60
            self.DURATION = 20  # Plus d'1 minute pour inclure le ralenti (initialement 60, mis à 20 pour test rapide)
            self.TOTAL_FRAMES = self.FPS * self.DURATION
            
            # Couleurs personnalisables des balles (facile à modifier)
            self.BALL_COLORS = {
                "Rouge": (255, 87, 87),
                "Vert": (87, 255, 87),
                "Bleu": (87, 87, 255),
                "Jaune": (255, 255, 87),
                "Rose": (255, 87, 255),
                "Cyan": (87, 255, 255),
                "Orange": (255, 165, 0),
                "Violet": (147, 112, 219),
                "Blanc": (255, 255, 255),
                "Or": (255, 215, 0)
            }
            
            # Textes d'engagement
            self.intro_text = "Quelle sera la balle qui arrivera en premier ?"
            self.intro_text2 = "Note ta couleur en commentaire ! 👇"
            self.outro_text = "Abonne-toi pour demander des couleurs personnalisées ! ❤️"
            
            # Variables de course
            self.balls = []
            self.maze_walls = []
            self.obstacles = []
            self.particles = []
            self.fireworks = []
            self.finish_line_y = 1750
            self.race_started = False
            self.race_finished = False
            self.winner = None
            self.slowmo_start = None
            
            # État du jeu
            self.current_text = ""
            self.text_timer = 0
            self.background_color = (15, 15, 25)
            
            # Initialisation Pygame pour vidéo
            # IMPORTANT: os.environ['SDL_AUDIODRIVER'] = 'dummy' peut empêcher l'audio de fonctionner
            # Si vous voulez entendre le son pendant la génération, commentez cette ligne,
            # mais cela peut causer des problèmes avec OpenCV et le rendu de la vidéo.
            os.environ['SDL_AUDIODRIVER'] = 'dummy'
            pygame.init()
            pygame.font.init()
            
            # Audio
            self.bounce_sound = None
            try:
                # Assurez-vous que 'bounce.wav' est dans le même dossier que le script
                # ou indiquez un chemin complet : par exemple, "C:/MonProjet/bounce.wav"
                self.bounce_sound = pygame.mixer.Sound('bounce.wav')
                pygame.mixer.set_num_channels(32) # Augmente le nombre de canaux pour les sons multiples
                print("Son 'bounce.wav' chargé avec succès.")
            except pygame.error as e:
                print(f"Erreur lors du chargement de 'bounce.wav': {e}. Le son ne sera pas joué.")
                print("Assurez-vous que le fichier 'bounce.wav' existe et que pygame.mixer est configuré correctement.")
            
            # Police pour les Emojis
            self.emoji_font_path = "C:\\Windows\\Fonts\\seguiemj.ttf" # Exemple pour Windows 10/11
            # Sur macOS, vous pourriez essayer : "/System/Library/Fonts/Apple Color Emoji.ttc"
            # Sur Linux, vous devrez trouver une police installée avec les emojis (ex: Noto Color Emoji)
            self.emoji_font = None
            try:
                self.emoji_font = pygame.font.Font(self.emoji_font_path, 64) # Taille de base
                print(f"Police emoji '{self.emoji_font_path}' chargée.")
            except FileNotFoundError:
                print(f"Police emoji non trouvée à '{self.emoji_font_path}'. Les emojis pourraient ne pas s'afficher correctement.")
                self.emoji_font = pygame.font.Font(None, 64) # Fallback vers la police par défaut
            except Exception as e:
                print(f"Erreur lors du chargement de la police emoji: {e}. Fallback vers la police par défaut.")
                self.emoji_font = pygame.font.Font(None, 64) # Fallback vers la police par défaut
    
    
        def create_ball(self, x, y, color_name, color):
            """Crée une balle de course"""
            return {
                'x': x,
                'y': y,
                'vx': 0,
                'vy': 0,
                'radius': 25,
                'color': color,
                'color_name': color_name,
                'trail': [],
                'speed': random.uniform(2.5, 4.0),  # Vitesse de base aléatoire
                'boost': 1.0,
                'stuck_timer': 0,
                'distance_traveled': 0,
                'finished': False,
                'finish_time': None
            }
        
        def create_maze(self):
            """Crée un labyrinthe en entonnoir avec murs inclinés vers l'intérieur"""
            walls = []
            
            # Murs extérieurs rectangulaires (haut et côtés)
            walls.append({'type': 'rect', 'x': 0, 'y': 0, 'width': self.WIDTH, 'height': 20})  # Haut
            walls.append({'type': 'rect', 'x': 0, 'y': 0, 'width': 20, 'height': self.HEIGHT})  # Gauche
            walls.append({'type': 'rect', 'x': self.WIDTH-20, 'y': 0, 'width': 20, 'height': self.HEIGHT})  # Droite
            
            # Définition des segments de l'entonnoir (y, largeur_chemin_à_ce_y)
            funnel_segments = [
                (300, self.WIDTH - 200),  # Début large
                (500, self.WIDTH - 300),
                (700, self.WIDTH - 400),
                (900, self.WIDTH - 500),
                (1100, self.WIDTH - 600),
                (1300, self.WIDTH - 700),
                (1500, self.WIDTH - 800),
                (self.finish_line_y - 50, 150) # Fin de l'entonnoir, juste avant la ligne d'arrivée
            ]
            
            wall_thickness = 40 # Épaisseur des murs de l'entonnoir
            
            for i in range(len(funnel_segments) - 1):
                y1, width1 = funnel_segments[i]
                y2, width2 = funnel_segments[i+1]
    
                # Calcul des x pour le chemin à y1 et y2 (centré)
                left_x_path1 = self.WIDTH / 2 - width1 / 2
                right_x_path1 = self.WIDTH / 2 + width1 / 2
    
                left_x_path2 = self.WIDTH / 2 - width2 / 2
                right_x_path2 = self.WIDTH / 2 + width2 / 2
    
                # Mur gauche de l'entonnoir (penche vers la droite / l'intérieur)
                p1 = (left_x_path1 - wall_thickness, y1) # Haut-gauche (extérieur)
                p2 = (left_x_path1, y1)                   # Haut-droite (intérieur)
                p3 = (left_x_path2, y2)                   # Bas-droite (intérieur)
                p4 = (left_x_path2 - wall_thickness, y2) # Bas-gauche (extérieur)
                
                # Convertir en int pour Pygame
                points_left = [(int(p[0]), int(p[1])) for p in [p1, p2, p3, p4]]
                
                # Calculer le bbox pour la détection de collision AABB préliminaire
                min_wall_x = min(p[0] for p in points_left)
                max_wall_x = max(p[0] for p in points_left)
                min_wall_y = min(p[1] for p in points_left)
                max_wall_y = max(p[1] for p in points_left)
                
                walls.append({
                    'type': 'funnel_wall',
                    'points': points_left,
                    'bbox': (min_wall_x, min_wall_y, max_wall_x - min_wall_x, max_wall_y - min_wall_y),
                    'is_left_side': True # Indique que c'est le mur gauche du chemin
                })
    
                # Mur droit de l'entonnoir (penche vers la gauche / l'intérieur)
                p1 = (right_x_path1, y1)                   # Haut-gauche (intérieur)
                p2 = (right_x_path1 + wall_thickness, y1) # Haut-droite (extérieur)
                p3 = (right_x_path2 + wall_thickness, y2) # Bas-droite (extérieur)
                p4 = (right_x_path2, y2)                   # Bas-gauche (intérieur)
    
                points_right = [(int(p[0]), int(p[1])) for p in [p1, p2, p3, p4]]
    
                min_wall_x = min(p[0] for p in points_right)
                max_wall_x = max(p[0] for p in points_right)
                min_wall_y = min(p[1] for p in points_right)
                max_wall_y = max(p[1] for p in points_right)
    
                walls.append({
                    'type': 'funnel_wall',
                    'points': points_right,
                    'bbox': (min_wall_x, min_wall_y, max_wall_x - min_wall_x, max_wall_y - min_wall_y),
                    'is_left_side': False # Indique que c'est le mur droit du chemin
                })
            
            # Obstacles mobiles (quelques-uns conservés mais ajustés pour le nouvel entonnoir)
            self.obstacles = [
                {'x': self.WIDTH / 2 - 100, 'y': 600, 'width': 40, 'height': 40, 'vx': 1.5, 'type': 'moving'},
                {'x': self.WIDTH / 2 + 50, 'y': 850, 'width': 50, 'height': 30, 'vx': -1.8, 'type': 'moving'},
                {'x': self.WIDTH / 2 - 70, 'y': 1100, 'width': 35, 'height': 35, 'vy': 1.2, 'type': 'moving'},
            ]
            
            # Assurez-vous que les obstacles ne sortent pas du funnel
            for obs in self.obstacles:
                if 'vx' in obs: obs['x'] = max(left_x_path1, min(obs['x'], right_x_path1 - obs['width']))
                if 'vy' in obs: obs['y'] = max(funnel_segments[0][0], min(obs['y'], funnel_segments[-1][0] - obs['height']))
    
            return walls
        
        def create_firework(self, x, y):
            """Crée un feu d'artifice"""
            colors = list(self.BALL_COLORS.values())
            for _ in range(50):
                angle = random.uniform(0, 2 * math.pi)
                speed = random.uniform(5, 15)
                self.fireworks.append({
                    'x': x,
                    'y': y,
                    'vx': math.cos(angle) * speed,
                    'vy': math.sin(angle) * speed,
                    'color': random.choice(colors),
                    'life': 60,
                    'size': random.randint(3, 8),
                    'gravity': random.uniform(0.1, 0.3)
                })
        
        def initialize_race(self):
            """Initialise la course avec les balles"""
            start_y = 200
            colors = list(self.BALL_COLORS.items())
            
            # Positionne les balles au-dessus de l'entonnoir
            num_balls = len(colors)
            spacing = (self.WIDTH - 200) / (num_balls + 1)
            for i, (name, color) in enumerate(colors):
                x = 100 + (i + 1) * spacing 
                ball = self.create_ball(x, start_y, name, color)
                self.balls.append(ball)
            
            # Crée le labyrinthe
            self.maze_walls = self.create_maze()
        
        def update_balls_physics(self):
            """Met à jour la physique des balles avec IA améliorée pour éviter les blocages"""
            if not self.race_started:
                return
            
            gravity = 1.2
            friction = 0.90
            
            for ball in self.balls:
                if ball['finished']:
                    continue
                    
                # Force principale vers le bas (gravité + biais)
                ball['vy'] += gravity
                ball['vy'] = min(ball['vy'], ball['speed'] * 2) # Limite la vitesse de chute
                
                # Mouvement horizontal aléatoire pour simuler la recherche de chemin
                ball['vx'] += random.uniform(-0.5, 0.5) * ball['speed'] * 0.1
                ball['vx'] = max(-ball['speed'], min(ball['speed'], ball['vx'])) # Limite vx
                
                # Applique le mouvement
                ball['x'] += ball['vx']
                ball['y'] += ball['vy']
                
                # Friction
                ball['vx'] *= friction
                ball['vy'] *= 0.98  # Moins de friction verticale
                
                # Gestion des blocages
                ball['stuck_timer'] += 1
                if ball['stuck_timer'] > 120: # Si bloqué pendant 2 secondes
                    # Tente de pousser la balle dans une direction aléatoire ou vers le bas
                    ball['vx'] = random.uniform(-ball['speed'] * 2, ball['speed'] * 2)
                    ball['vy'] = ball['speed'] * 3 # Pousse fort vers le bas
                    ball['stuck_timer'] = 0
                    print(f"Anti-blocage agressif activé pour {ball['color_name']}")
    
                # Collision avec les murs externes rectangulaires
                if ball['x'] - ball['radius'] <= 20:
                    ball['x'] = 20 + ball['radius']
                    ball['vx'] = abs(ball['vx']) * 0.8 # Rebond
                    self.play_collision_sound()
                    self.create_particle_explosion(ball['x'], ball['y'], ball['color'])
                
                if ball['x'] + ball['radius'] >= self.WIDTH - 20:
                    ball['x'] = self.WIDTH - 20 - ball['radius']
                    ball['vx'] = -abs(ball['vx']) * 0.8 # Rebond
                    self.play_collision_sound()
                    self.create_particle_explosion(ball['x'], ball['y'], ball['color'])
                
                # Collision avec les murs du labyrinthe (rectangle ou entonnoir)
                for wall in self.maze_walls:
                    wall_x, wall_y, wall_width, wall_height = wall['bbox'] # Bounding box pour le check rapide
    
                    # Check de collision AABB (Axis-Aligned Bounding Box)
                    if (ball['x'] + ball['radius'] > wall_x and 
                        ball['x'] - ball['radius'] < wall_x + wall_width and
                        ball['y'] + ball['radius'] > wall_y and 
                        ball['y'] - ball['radius'] < wall_y + wall_height):
                        
                        if wall['type'] == 'rect':
                            # Logique de collision existante pour les murs rectangulaires
                            center_x = wall_x + wall_width / 2
                            center_y = wall_y + wall_height / 2
                            
                            dx = ball['x'] - center_x
                            dy = ball['y'] - center_y
                            
                            if abs(dx) > abs(dy): # Collision horizontale dominante
                                direction = 1 if dx > 0 else -1
                                ball['vx'] = ball['speed'] * direction * 1.5 # Rebond plus fort
                                ball['vy'] = ball['speed'] * 0.5 # Poussée légère vers le bas
                                # Repositionnement
                                ball['x'] = wall_x + (wall_width + ball['radius'] + 5 if dx > 0 else -ball['radius'] - 5)
                            else: # Collision verticale dominante
                                if dy > 0: # Balle en dessous du mur
                                    ball['vy'] = ball['speed'] * 1.2 # Pousse vers le bas
                                    ball['y'] = wall_y + wall_height + ball['radius'] + 5
                                else: # Balle au-dessus du mur
                                    ball['vy'] = -ball['speed'] * 0.3 # Léger rebond vers le haut
                                    ball['y'] = wall_y - ball['radius'] - 5
                            self.play_collision_sound()
                            self.create_particle_explosion(ball['x'], ball['y'], ball['color'])
    
                        elif wall['type'] == 'funnel_wall':
                            # Logique de collision pour les murs inclinés de l'entonnoir
                            bounce_strength_x = ball['speed'] * 1.5 # Force de rebond horizontal
                            downward_push_y = ball['speed'] * 0.7 # Force de poussée vers le bas
    
                            if wall['is_left_side']: # Mur gauche de l'entonnoir (pousse vers la droite et le bas)
                                ball['vx'] = abs(ball['vx']) * bounce_strength_x # Force vers la droite
                                # Repositionnement pour éviter de rester bloqué
                                ball['x'] = max(ball['x'], wall_x + wall_width + ball['radius'] + 2) 
                            else: # Mur droit de l'entonnoir (pousse vers la gauche et le bas)
                                ball['vx'] = -abs(ball['vx']) * bounce_strength_x # Force vers la gauche
                                # Repositionnement
                                ball['x'] = min(ball['x'], wall_x - ball['radius'] - 2) 
                            
                            # Ajoute une forte poussée vers le bas pour simuler l'entonnoir
                            ball['vy'] = abs(ball['vy']) * 0.5 + downward_push_y 
                            
                            self.play_collision_sound()
                            self.create_particle_explosion(ball['x'], ball['y'], ball['color'])
                        
                        ball['stuck_timer'] = 0 # Réinitialise le timer anti-blocage
    
                # Collision avec les obstacles mobiles
                for obstacle in self.obstacles:
                    if (ball['x'] + ball['radius'] > obstacle['x'] and 
                        ball['x'] - ball['radius'] < obstacle['x'] + obstacle['width'] and
                        ball['y'] + ball['radius'] > obstacle['y'] and 
                        ball['y'] - ball['radius'] < obstacle['y'] + obstacle['height']):
                        
                        # Simple rebond
                        center_obs_x = obstacle['x'] + obstacle['width'] / 2
                        center_obs_y = obstacle['y'] + obstacle['height'] / 2
                        
                        dx = ball['x'] - center_obs_x
                        dy = ball['y'] - center_obs_y
                        
                        if abs(dx) > abs(dy): # Collision horizontale
                            ball['vx'] *= -1.5 # Rebond fort
                            ball['x'] += dx / abs(dx) * (ball['radius'] + 5) # Éloigne la balle
                        else: # Collision verticale
                            ball['vy'] *= -1.5 # Rebond fort
                            ball['y'] += dy / abs(dy) * (ball['radius'] + 5) # Éloigne la balle
                        
                        self.play_collision_sound()
                        self.create_particle_explosion(ball['x'], ball['y'], ball['color'])
    
                # Traînée
                ball['trail'].append((int(ball['x']), int(ball['y'])))
                if len(ball['trail']) > 15: # Traînées plus longues
                    ball['trail'].pop(0)
                
                # Vérifie la ligne d'arrivée
                if ball['y'] >= self.finish_line_y and not ball['finished']:
                    ball['finished'] = True
                    ball['finish_time'] = pygame.time.get_ticks()
                    
                    if not self.race_finished: # C'est le premier à finir
                        self.winner = ball
                        self.race_finished = True
                        self.slowmo_start = pygame.time.get_ticks()
                        
                        # Crée des feux d'artifice
                        for _ in range(8): # Plus de feux d'artifice
                            self.create_firework(
                                random.randint(100, self.WIDTH-100),
                                random.randint(self.finish_line_y-250, self.finish_line_y-50)
                            )
        
        def update_obstacles(self):
            """Met à jour les obstacles mobiles"""
            # Limite les mouvements des obstacles pour qu'ils restent dans le funnel
            max_path_width = self.WIDTH - 200 # Largeur max au départ
            min_path_width = 150 # Largeur min à l'arrivée
            
            for obstacle in self.obstacles:
                if obstacle['type'] == 'moving':
                    
                    # Calculer la largeur du chemin à la hauteur de l'obstacle pour limiter son mouvement
                    current_y_ratio = (obstacle['y'] - 300) / (self.finish_line_y - 300 - 50) # Normalise y de 0 à 1
                    current_y_ratio = max(0, min(1, current_y_ratio)) # Clampe entre 0 et 1
    
                    current_path_width = max_path_width - (max_path_width - min_path_width) * current_y_ratio
                    left_boundary = self.WIDTH / 2 - current_path_width / 2 + 20 # 20 pour la bordure externe
                    right_boundary = self.WIDTH / 2 + current_path_width / 2 - 20
    
                    if 'vx' in obstacle:
                        obstacle['x'] += obstacle['vx']
                        if obstacle['x'] <= left_boundary or obstacle['x'] + obstacle['width'] >= right_boundary:
                            obstacle['vx'] *= -1
                            # Repositionne pour éviter le "collage"
                            if obstacle['x'] <= left_boundary: obstacle['x'] = left_boundary + 1
                            if obstacle['x'] + obstacle['width'] >= right_boundary: obstacle['x'] = right_boundary - obstacle['width'] - 1
                    
                    if 'vy' in obstacle:
                        obstacle['y'] += obstacle['vy']
                        # Limite verticale pour rester dans l'entonnoir
                        min_y_limit = 350 # Début de l'entonnoir
                        max_y_limit = self.finish_line_y - 100 # Un peu avant la ligne d'arrivée
                        
                        if obstacle['y'] <= min_y_limit or obstacle['y'] + obstacle['height'] >= max_y_limit:
                            obstacle['vy'] *= -1
                            if obstacle['y'] <= min_y_limit: obstacle['y'] = min_y_limit + 1
                            if obstacle['y'] + obstacle['height'] >= max_y_limit: obstacle['y'] = max_y_limit - obstacle['height'] - 1
    
        def create_particle_explosion(self, x, y, color):
            """Crée une explosion de particules"""
            for _ in range(20): # Plus de particules
                angle = random.uniform(0, 2 * math.pi)
                speed = random.uniform(3, 8) # Plus rapide
                self.particles.append({
                    'x': x,
                    'y': y,
                    'vx': math.cos(angle) * speed,
                    'vy': math.sin(angle) * speed,
                    'color': color,
                    'life': 25, # Plus longue durée de vie
                    'size': random.randint(3, 6)
                })
        
        def update_particles(self):
            """Met à jour les particules"""
            for particle in self.particles[:]:
                particle['x'] += particle['vx']
                particle['y'] += particle['vy']
                particle['vy'] += 0.3 # Gravité plus forte pour les particules
                particle['life'] -= 1
                particle['size'] = max(1, particle['size'] - 0.15) # Rétrécissement plus rapide
                
                if particle['life'] <= 0:
                    self.particles.remove(particle)
        
        def update_fireworks(self):
            """Met à jour les feux d'artifice"""
            for firework in self.fireworks[:]:
                firework['x'] += firework['vx']
                firework['y'] += firework['vy']
                firework['vy'] += firework['gravity']
                firework['life'] -= 1
                firework['size'] = max(1, firework['size'] - 0.1)
                
                if firework['life'] <= 0:
                    self.fireworks.remove(firework)
        
        def play_collision_sound(self):
            """Joue le son de collision"""
            if self.bounce_sound:
                self.bounce_sound.play()
        
        def generate_scenario(self, frame):
            """Génère le scénario selon le moment"""
            # Texte d'introduction (5 premières secondes)
            if frame == 30:
                self.current_text = self.intro_text
                self.text_timer = 180
            
            if frame == 180:
                self.current_text = self.intro_text2
                self.text_timer = 120
            
            # Début de la course
            if frame == 300:  # 5 secondes
                self.race_started = True
                self.current_text = "C'est parti ! 🏁"
                self.text_timer = 60
            
            # Messages d'encouragement
            if frame == 900:  # 15 secondes
                self.current_text = "Qui va gagner ? 🤔"
                self.text_timer = 90
            
            if frame == 1800:  # 30 secondes
                self.current_text = "Ça se resserre ! 🔥"
                self.text_timer = 90
            
            if frame == 2400:  # 40 secondes
                self.current_text = "Presque arrivé ! 🏃💨"
                self.text_timer = 90
            
            # Force la fin si trop long (sécurité)
            # La durée totale est maintenant de 20s = 1200 frames. Ajuster la sécurité.
            if frame > self.TOTAL_FRAMES - 300 and not self.race_finished:  # Force la fin dans les dernières 5s
                # Trie les balles par y pour déterminer un "pseudo-gagnant" si personne n'a fini
                sorted_balls = sorted([b for b in self.balls if not b['finished']], key=lambda b: b['y'], reverse=True)
                if sorted_balls:
                    forced_winner = sorted_balls[0]
                    forced_winner['y'] = self.finish_line_y + 10 # Pousse le "gagnant"
                    forced_winner['finished'] = True
                    forced_winner['finish_time'] = pygame.time.get_ticks()
                    self.winner = forced_winner
                    self.race_finished = True
                    self.slowmo_start = pygame.time.get_ticks() # Simule le moment de la fin
    
                    # Crée des feux d'artifice
                    for _ in range(5):
                        self.create_firework(
                            random.randint(100, self.WIDTH-100),
                            random.randint(self.finish_line_y-200, self.finish_line_y-50)
                        )
                else: # Toutes les balles sont déjà finies, mais race_finished est encore False
                    self.race_finished = True
    
    
            # Texte de fin
            if self.race_finished and frame > self.TOTAL_FRAMES - 250: # Apparaît 4s avant la fin
                if self.winner:
                    self.current_text = f"🏆 {self.winner['color_name']} GAGNE ! 🏆"
                    self.text_timer = 180 # Reste 3 secondes
            
            # Message d'abonnement final
            if frame > self.TOTAL_FRAMES - 120: # Apparaît dans les dernières 2 secondes
                self.current_text = self.outro_text
                self.text_timer = 120 # Reste 2 secondes
        
        def draw_frame(self, surface):
            """Dessine un frame"""
            # Fond dégradé
            for y in range(self.HEIGHT):
                color_factor = y / self.HEIGHT
                r = int(self.background_color[0] + color_factor * 30)
                g = int(self.background_color[1] + color_factor * 30)
                b = int(self.background_color[2] + color_factor * 60)
                pygame.draw.line(surface, (r, g, b), (0, y), (self.WIDTH, y))
            
            # Dessine le labyrinthe
            for wall in self.maze_walls:
                if wall['type'] == 'rect':
                    pygame.draw.rect(surface, (100, 100, 120), 
                                   (wall['x'], wall['y'], wall['width'], wall['height']))
                    pygame.draw.rect(surface, (150, 150, 180), 
                                   (wall['x'], wall['y'], wall['width'], wall['height']), 3)
                elif wall['type'] == 'funnel_wall':
                    # Dessine le polygone du mur incliné
                    pygame.draw.polygon(surface, (100, 100, 120), wall['points'])
                    pygame.draw.polygon(surface, (150, 150, 180), wall['points'], 3)
            
            # Dessine les obstacles mobiles
            for obstacle in self.obstacles:
                pygame.draw.rect(surface, (200, 100, 100), 
                               (obstacle['x'], obstacle['y'], obstacle['width'], obstacle['height']))
                pygame.draw.rect(surface, (255, 150, 150), 
                               (obstacle['x'], obstacle['y'], obstacle['width'], obstacle['height']), 2)
            
            # Ligne d'arrivée
            for i in range(0, self.WIDTH, 40):
                color = (255, 255, 255) if (i // 40) % 2 == 0 else (0, 0, 0)
                pygame.draw.rect(surface, color, (i, self.finish_line_y-10, 40, 20))
            
            # Dessine les particules
            for particle in self.particles:
                if particle['life'] > 0:
                    alpha = particle['life'] / 25.0 # Basé sur la nouvelle durée de vie
                    color = (int(particle['color'][0] * alpha), 
                             int(particle['color'][1] * alpha), 
                             int(particle['color'][2] * alpha))
                    pygame.draw.circle(surface, color, 
                                     (int(particle['x']), int(particle['y'])), 
                                     int(particle['size']))
            
            # Dessine les feux d'artifice
            for firework in self.fireworks:
                if firework['life'] > 0:
                    alpha = firework['life'] / 60.0
                    color = (int(firework['color'][0] * alpha),
                             int(firework['color'][1] * alpha),
                             int(firework['color'][2] * alpha))
                    pygame.draw.circle(surface, color,
                                     (int(firework['x']), int(firework['y'])),
                                     int(firework['size']))
            
            # Dessine les traînées des balles
            for ball in self.balls:
                if len(ball['trail']) > 1: # S'assurer qu'il y a au moins 2 points pour une ligne
                    for i in range(1, len(ball['trail'])):
                        alpha = i / len(ball['trail'])
                        color = tuple(int(c * alpha) for c in ball['color'])
                        pygame.draw.line(surface, color, 
                                       ball['trail'][i-1], ball['trail'][i], 4) # Lignes plus épaisses
            
            # Dessine les balles
            for ball in self.balls:
                # Aura pour le gagnant
                if ball == self.winner:
                    glow_radius = ball['radius'] + 15 + int(8 * math.sin(pygame.time.get_ticks() / 100))
                    glow_color = tuple(c // 2 for c in ball['color'])
                    pygame.draw.circle(surface, glow_color, 
                                     (int(ball['x']), int(ball['y'])), glow_radius)
                
                # Balle principale
                pygame.draw.circle(surface, ball['color'], 
                                 (int(ball['x']), int(ball['y'])), ball['radius'])
                
                # Reflet
                highlight_color = tuple(min(255, c + 80) for c in ball['color'])
                pygame.draw.circle(surface, highlight_color, 
                                 (int(ball['x'] - ball['radius']//3), 
                                  int(ball['y'] - ball['radius']//3)), 
                                 ball['radius']//4)
                
                # Nom de la couleur sur la balle
                font = pygame.font.Font(None, 24)
                text = font.render(ball['color_name'][:3], True, (0, 0, 0))
                text_rect = text.get_rect(center=(int(ball['x']), int(ball['y'])))
                surface.blit(text, text_rect)
        
        def draw_text(self, surface):
            """Dessine le texte d'engagement"""
            if self.text_timer > 0:
                font_to_use = self.emoji_font # Utilisez la police emoji chargée
                font_size = 64 if len(self.current_text) < 30 else 48
                
                # Mise à jour de la taille de la police pour le texte non-emoji
                # Si on a une police emoji, on peut la redimensionner à la volée
                if font_to_use:
                    font_to_use = pygame.font.Font(font_to_use.get_path(), font_size)
                else: # Fallback pour la police par défaut si emoji_font_path est None ou vide
                    font_to_use = pygame.font.Font(None, font_size)
    
                # Divise le texte en lignes si nécessaire (pour les messages longs)
                lines = []
                max_line_width = self.WIDTH - 100 # Marge
                
                words = self.current_text.split()
                current_line = ""
                for word in words:
                    test_line = current_line + word + " "
                    if font_to_use.size(test_line)[0] < max_line_width:
                        current_line = test_line
                    else:
                        lines.append(current_line.strip())
                        current_line = word + " "
                lines.append(current_line.strip()) # Ajoute la dernière ligne
                
                # Dessine chaque ligne
                for i, line in enumerate(lines):
                    text_surface = font_to_use.render(line, True, (255, 255, 255))
                    
                    # Ombre
                    shadow_surface = font_to_use.render(line, True, (0, 0, 0))
                    y_pos = 100 + (i * (font_size + 10)) # Espacement basé sur la taille de la police
                    surface.blit(shadow_surface, (self.WIDTH//2 - text_surface.get_width()//2 + 3, y_pos + 3))
                    
                    # Texte principal
                    surface.blit(text_surface, (self.WIDTH//2 - text_surface.get_width()//2, y_pos))
                
                self.text_timer -= 1
        
        def generate_video(self, output_path="maze_ball_race.mp4"):
            """Génère la vidéo complète"""
            # Initialise la course
            self.initialize_race()
            
            # Crée une surface pour le rendu
            surface = pygame.Surface((self.WIDTH, self.HEIGHT))
            
            # Configuration de l'enregistrement vidéo
            fourcc = cv2.VideoWriter_fourcc(*'mp4v')
            out = cv2.VideoWriter(output_path, fourcc, self.FPS, (self.WIDTH, self.HEIGHT))
            
            print(f"Génération de la vidéo de course: {self.DURATION}s à {self.FPS}fps...")
            print("Cela peut prendre quelques minutes...")
            
            for frame in range(self.TOTAL_FRAMES):
                # Génère le scénario
                self.generate_scenario(frame)
                
                # Met à jour la physique
                self.update_balls_physics()
                self.update_obstacles()
                self.update_particles()
                self.update_fireworks()
                
                # Dessine le frame
                self.draw_frame(surface)
                self.draw_text(surface)
                
                # Convertit en format OpenCV
                frame_array = pygame.surfarray.array3d(surface)
                frame_array = np.rot90(frame_array)
                frame_array = np.flipud(frame_array)
                frame_array = cv2.cvtColor(frame_array, cv2.COLOR_RGB2BGR)
                
                # Écrit le frame
                out.write(frame_array)
                
                # Affiche le progrès
                if frame % (self.FPS * 2) == 0 or frame == self.TOTAL_FRAMES - 1: # Affiche plus souvent
                    progress = (frame / self.TOTAL_FRAMES) * 100
                    print(f"Progrès: {progress:.1f}%")
            
            # Finalise la vidéo
            out.release()
            pygame.quit()
            
            print(f"Vidéo de course générée avec succès: {output_path}")
            return output_path
    
    def create_custom_maze_race(custom_colors=None):
        """Crée une vidéo de course avec des couleurs personnalisées"""
        generator = MazeBallRaceGenerator()
        
        # Applique les couleurs personnalisées si fournies
        if custom_colors:
            generator.BALL_COLORS.update(custom_colors)
        
        # Génère un nom de fichier unique
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        output_path = f"maze_ball_race_{timestamp}.mp4"
        
        return generator.generate_video(output_path)
    
    # Script principal
    if __name__ == "__main__":
        print("🏁 GÉNÉRATEUR DE COURSE DE BALLES DANS UN LABYRINTHE 🏁")
        print("=" * 60)
        
        # Exemple avec couleurs personnalisées
        # custom_colors = {
        #     "Turquoise": (64, 224, 208),
        #     "Corail": (255, 127, 80),
        #     "Lavande": (230, 230, 250)
        # }
        
        try:
            print("🎬 Génération en cours...")
            # video_path = create_custom_maze_race(custom_colors)  # Avec couleurs custom
            video_path = create_custom_maze_race()  # Couleurs par défaut
            
            print(f"\n✅ Succès! Votre vidéo de course est prête: {video_path}")
            print("\n🚀 Conseils pour maximiser l'engagement:")
            print("- Titre: 'Quelle couleur va gagner? 🏁'")
            print("- Hashtags: #ballrace #satisfying #maze #fyp #challenge")
            print("- Description: 'Note ta couleur préférée en commentaire!'")
            print("- Répondez aux commentaires avec des encouragements")
            print("- Proposez des couleurs personnalisées pour les abonnés")
            
            print(f"\n🎨 Couleurs disponibles: {', '.join(MazeBallRaceGenerator().BALL_COLORS.keys())}")
            
        except Exception as e:
            print(f"❌ Erreur lors de la génération: {e}")
            print("Vérifiez que les dépendances sont installées:")
            print("pip install pygame opencv-python numpy")
            print("Et que le fichier 'bounce.wav' est présent dans le répertoire du script.")
            print("Si les emojis ne fonctionnent pas, vérifiez le chemin de la police emoji dans le code.")
    
    

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.