💻 Ejemplos de Código Innovadores 💻 Innovative Code Examples

Showcase de las soluciones más interesantes generadas por IA Showcase of the most interesting AI-generated solutions

Sistema de IA Híbrido Hybrid AI System

Desafío: Crear enemigos inteligentes que sean desafiantes pero predecibles. Challenge: Create intelligent enemies that are challenging but predictable.

Solución de IA: Sistema híbrido que combina lógica basada en reglas con validación Q-Learning. AI Solution: Hybrid system combining rule-based logic with Q-Learning validation.

def barrel_movement(self, platforms, player_rect=None):
    """IA Híbrida: Decisiones primarias basadas en reglas con validación Q-Learning"""
    if not player_rect or not platforms:
        self.velocity_x = self.speed * self.direction
        return
    
    # PASO 1: Decisión primaria basada en reglas
    dx = player_rect.centerx - self.rect.centerx
    dy = player_rect.centery - self.rect.centery
    primary_action = self.decide_primary_action(dx, dy, current_platform, player_platform)
    
    # PASO 2: Validación y mejora con Q-Learning
    if hasattr(self, 'ai_agent'):
        state = self.get_state(player_rect)
        q_action = self.ai_agent.choose_action(state)
        
        # Anular solo en situaciones específicas
        if self.should_override_action(primary_action, q_action, dx, dy):
            primary_action = q_action
        
        # Aprender de la acción tomada
        reward = self.calculate_reward(player_rect)
        next_state = self.get_state(player_rect)
        self.ai_agent.learn(state, primary_action, reward, next_state, not self.active)
    
    # PASO 3: Ejecutar la acción decidida
    self.execute_action_decision(primary_action, current_platform, dx)

Por qué esto es Innovador: Why this is Innovative:

  • Lo mejor de ambos mundos: Comportamiento base predecible con mejoras adaptativas Best of both worlds: Predictable base behavior with adaptive improvements
  • Aprendizaje contextual: Q-Learning solo anula cuando tiene alta confianza Contextual learning: Q-Learning only overrides when highly confident
  • Experiencia del jugador: Mantiene la sensación del juego mientras agrega inteligencia Player experience: Maintains game feel while adding intelligence
  • Amigable para debugging: El núcleo basado en reglas es fácil de entender y modificar Debug-friendly: Rule-based core is easy to understand and modify

Carga Dinámica de Assets Dynamic Asset Loading

Desafío: Assets que no cargan en ejecutables empaquetados debido a diferencias de rutas. Challenge: Assets not loading in packaged executables due to path differences.

Solución de IA: Resolución dinámica de rutas que funciona tanto en desarrollo como en producción. AI Solution: Dynamic path resolution that works in both development and production.

def load_sprites(self):
    """Carga dinámica de assets para desarrollo y ejecutables empaquetados""""""Dynamic asset loading for development and packaged executables"""
    sprites = {'idle': [], 'jump': []}
    
    # PASO 1: Determinar la ruta base correcta# STEP 1: Determine correct base path
    if hasattr(sys, '_MEIPASS'):
        # Ejecutable empaquetado con PyInstaller# PyInstaller packaged executable
        base_path = sys._MEIPASS
        print("Cargando assets desde ejecutable empaquetado")print("Loading assets from packaged executable")
    else:
        # Entorno de desarrollo# Development environment
        base_path = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
        print("Cargando assets desde directorio de desarrollo")print("Loading assets from development directory")
    
    # PASO 2: Cargar sprites con manejo comprensivo de errores# STEP 2: Load sprites with comprehensive error handling
    for i in range(1, 12):
        sprite_path = os.path.join(base_path, 'assets', 'player', f'sprite_{i:02d}.png')
        
        if os.path.exists(sprite_path):
            try:
                sprite = pygame.image.load(sprite_path)
                sprite = pygame.transform.scale(sprite, (self.rect.width, self.rect.height))
                sprites['jump'].append(sprite)
                print(f"✓ Sprite cargado: sprite_{i:02d}.png")print(f"✓ Sprite loaded: sprite_{i:02d}.png")
            except Exception as e:
                print(f"✗ Error cargando sprite {sprite_path}: {e}")print(f"✗ Error loading sprite {sprite_path}: {e}")
                # Continuar cargando otros sprites# Continue loading other sprites
        else:
            print(f"⚠ Sprite no encontrado: {sprite_path}")print(f"⚠ Sprite not found: {sprite_path}")
    
    return sprites if any(sprites.values()) else None

def load_asset_safely(self, asset_path, default_size=(32, 32)):
    """Carga segura de assets con fallback""""""Safe asset loading with fallback"""
    try:
        if os.path.exists(asset_path):
            asset = pygame.image.load(asset_path)
            return pygame.transform.scale(asset, default_size)
    except Exception as e:
        print(f"Falló la carga de asset para {asset_path}: {e}")print(f"Asset loading failed for {asset_path}: {e}")
    
    # Retornar rectángulo coloreado como fallback# Return colored rectangle as fallback
    surface = pygame.Surface(default_size)
    surface.fill((255, 0, 255))  # Magenta para assets faltantessurface.fill((255, 0, 255))  # Magenta for missing assets
    return surface

Por qué esto es Innovador: Why this is Innovative:

  • Compatibilidad universal: Funciona en desarrollo y ejecutables empaquetados Universal compatibility: Works in development and packaged executables
  • Degradación elegante: Continúa funcionando incluso con assets faltantes Graceful degradation: Continues working even with missing assets
  • Logging detallado: Proporciona retroalimentación clara sobre el estado de carga de assets Detailed logging: Provides clear feedback on asset loading status
  • Sistema de fallback: Nunca crashea debido a assets faltantes Fallback system: Never crashes due to missing assets

Spawn Inteligente de Enemigos Intelligent Enemy Spawning

Desafío: Equilibrar la dificultad de enemigos sin abrumar al jugador. Challenge: Balance enemy difficulty without overwhelming the player.

Solución de IA: Sistema de spawn adaptativo que escala con el tiempo y rendimiento del jugador. AI Solution: Adaptive spawning system that scales with time and player performance.

def spawn_entities(self):
    """Spawn inteligente de entidades con dificultad adaptativa""""""Intelligent entity spawning with adaptive difficulty"""
    self.spawn_timer += 1
    
    # SPAWN ADAPTATIVO DE BARRILES# ADAPTIVE BARREL SPAWNING
    self.spawn_barrels_adaptively()
    
    # SPAWN GRADUAL DE MONSTRUOS# GRADUAL MONSTER SPAWNING
    self.spawn_monsters_gradually()

def spawn_barrels_adaptively(self):
    """Spawn de barriles con dificultad creciente en el tiempo""""""Barrel spawning with increasing difficulty over time"""
    barrel_count = len([e for e in self.enemies if e.enemy_type == "barrel"])
    
    # Calcular máximo de barriles basado en tiempo jugado# Calculate maximum barrels based on play time
    time_factor = self.spawn_timer // 3600  # Cada 60 segundos# Every 60 seconds
    max_barrels = min(1 + time_factor, 3)  # Máximo 3 barriles# Maximum 3 barrels
    
    # Calcular tasa de spawn (aumenta con el tiempo)# Calculate spawn rate (increases with time)
    current_spawn_rate = min(
        self.base_spawn_rate + (time_factor * self.spawn_rate_increase),
        self.max_spawn_rate
    )
    
    # Spawn si está bajo el límite y pasa la verificación de probabilidad# Spawn if under limit and passes probability check
    if barrel_count < max_barrels and random.random() < current_spawn_rate:
        self.spawn_barrel()
        print(f"Barril spawneado (Tasa: {current_spawn_rate:.3f}, Cantidad: {barrel_count + 1}/{max_barrels})")print(f"Barrel spawned (Rate: {current_spawn_rate:.3f}, Count: {barrel_count + 1}/{max_barrels})")

Por qué esto es Innovador: Why this is Innovative:

  • Dificultad adaptativa: La tasa de spawn aumenta con el tiempo jugado Adaptive difficulty: Spawn rate increases with play time
  • Posicionamiento estratégico: Los enemigos aparecen lejos del jugador para mejor desafío Strategic positioning: Enemies spawn away from player for better challenge
  • Progresión equilibrada: El aumento gradual previene abrumar Balanced progression: Gradual increase prevents overwhelming
  • Monitoreo de rendimiento: Estadísticas integradas para ajustes Performance monitoring: Built-in statistics for tuning

Q-Learning sin NumPy Q-Learning without NumPy

Desafío: Conflictos de PyInstaller con NumPy causando errores de empaquetado. Challenge: PyInstaller conflicts with NumPy causing packaging errors.

Solución de IA: Implementación de Q-Learning usando solo Python estándar. AI Solution: Q-Learning implementation using only standard Python.

class SimpleArray:
    """Reemplazo simple de NumPy para empaquetado""""""Simple NumPy replacement for packaging"""
    def __init__(self, data):
        self.data = data if isinstance(data, list) else [data]
    
    def argmax(self):
        """Encuentra el índice del valor máximo""""""Find index of maximum value"""
        if not self.data:
            return 0
        max_val = max(self.data)
        return self.data.index(max_val)
    
    def zeros(self, shape):
        """Crea array de ceros""""""Create array of zeros"""
        if isinstance(shape, int):
            return [0.0] * shape
        return [[0.0] * shape[1] for _ in range(shape[0])]

class QLearningAgent:
    def __init__(self, state_size, action_size, learning_rate=0.1):
        self.state_size = state_size
        self.action_size = action_size
        self.learning_rate = learning_rate
        self.discount_factor = 0.95
        self.epsilon = 0.1
        self.q_table = {}
    
    def choose_action(self, state):
        """Selección de acción epsilon-greedy sin NumPy""""""Epsilon-greedy action selection without NumPy"""
        state_key = self.get_state_key(state)
        
        if random.random() < self.epsilon:
            return random.randint(0, self.action_size - 1)
        
        if state_key not in self.q_table:
            self.q_table[state_key] = [0.0] * self.action_size
        
        # Usar implementación manual de argmax# Use manual argmax implementation
        q_values = self.q_table[state_key]
        max_value = max(q_values)
        return q_values.index(max_value)

Por qué esto es Innovador: Why this is Innovative:

  • Solución de compatibilidad: Elimina conflictos de dependencias de PyInstaller Compatibility solution: Eliminates PyInstaller dependency conflicts
  • Rendimiento mantenido: Funcionalidad completa sin bibliotecas externas Maintained performance: Full functionality without external libraries
  • Simplicidad: Más fácil de debuggear y entender Simplicity: Easier to debug and understand
  • Portabilidad: Funciona en cualquier instalación de Python Portability: Works on any Python installation

Conclusión Conclusion

Estos ejemplos demuestran cómo la IA puede generar código sofisticado y listo para producción que maneja la complejidad del mundo real y casos edge de manera efectiva. Las soluciones van más allá de la funcionalidad básica para incluir: These examples demonstrate how AI can generate sophisticated, production-ready code that handles real-world complexity and edge cases effectively. The solutions go beyond basic functionality to include:

La clave está en proporcionar contexto rico y requerimientos específicos a la IA, permitiéndole generar soluciones que no solo funcionan, sino que son mantenibles, extensibles y profesionales. The key is providing rich context and specific requirements to AI, allowing it to generate solutions that not only work but are maintainable, extensible, and professional.