🤖 Algoritmos de Inteligencia Artificial 🤖 Artificial Intelligence Algorithms

Implementación de Q-Learning y sistemas híbridos para enemigos inteligentes Q-Learning implementation and hybrid systems for intelligent enemies

Visión General Overview

El juego implementa un sistema de IA híbrido que combina lógica basada en reglas con aprendizaje por refuerzo (Q-Learning) para crear comportamientos de enemigos inteligentes que se adaptan a los patrones del jugador. The game implements a hybrid AI system that combines rule-based logic with reinforcement learning (Q-Learning) to create intelligent enemy behaviors that adapt to player patterns.

Algoritmo Q-Learning Q-Learning Algorithm

¿Qué es Q-Learning? What is Q-Learning?

Q-Learning es un algoritmo de aprendizaje por refuerzo libre de modelo que aprende la calidad de las acciones, indicando a un agente qué acción tomar bajo qué circunstancias. Q-Learning is a model-free reinforcement learning algorithm that learns the quality of actions, telling an agent what action to take under what circumstances.

Detalles de Implementación Implementation Details

Espacio de Estados State Space

El agente de IA observa un espacio de estados de 6 dimensiones: The AI agent observes a 6-dimensional state space:

state = [
    enemy_x / window_width,      # Posición X normalizada del enemigo (0-1)
    enemy_y / window_height,     # Posición Y normalizada del enemigo (0-1)
    player_x / window_width,     # Posición X normalizada del jugador (0-1)
    player_y / window_height,    # Posición Y normalizada del jugador (0-1)
    (direction + 1) / 2,         # Dirección normalizada (-1,1) → (0,1)
    1 if on_ground else 0        # Contacto con el suelo (booleano)
]

Espacio de Acciones Action Space

El agente puede elegir entre 4 acciones posibles: The agent can choose from 4 possible actions:

actions = {
    0: "Mover Izquierda",    # Mover enemigo a la izquierda
    1: "Mover Derecha",      # Mover enemigo a la derecha
    2: "Saltar",             # Saltar a plataforma superior
    3: "Caer/Esperar"        # Caer a plataforma inferior o esperar
}

Función de Recompensa Reward Function

El sistema de recompensas incentiva a la IA a acercarse al jugador: The reward system incentivizes the AI to get closer to the player:

def calculate_reward(self, player_rect):
    if player_rect is None:
        return -0.1
    
    # Recompensa basada en distancia
    distance = sqrt((enemy_x - player_x)² + (enemy_y - player_y)²)
    max_distance = sqrt(window_width² + window_height²)
    proximity_reward = (max_distance - distance) / max_distance
    
    # Bonus por estar en la misma plataforma
    same_platform_bonus = 0.3 if abs(enemy_y - player_y) < 30 else 0
    
    # Penalización por estar atascado
    stuck_penalty = -0.2 if stuck_timer > 60 else 0
    
    return proximity_reward + same_platform_bonus + stuck_penalty

Arquitectura de IA Híbrida Hybrid AI Architecture

Sistema de Decisión Primario (Basado en Reglas) Primary Decision System (Rule-Based)

La IA utiliza lógica basada en reglas como sistema principal de toma de decisiones: The AI uses rule-based logic as the main decision-making system:

def decide_primary_action(self, dx, dy, current_platform, player_platform):
    # Forzar caída si está en el borde de la plataforma
    if at_platform_edge():
        return DROP_ACTION
    
    # Saltar si el jugador está arriba
    if dy < -40 and abs(dx) < 100:
        return JUMP_ACTION
    
    # Moverse horizontalmente hacia el jugador
    if abs(dx) > 10:
        return RIGHT_ACTION if dx > 0 else LEFT_ACTION
    
    return RIGHT_ACTION  # Comportamiento por defecto

Sistema de Validación Q-Learning Q-Learning Validation System

Q-Learning actúa como una capa de validación y mejora: Q-Learning acts as a validation and improvement layer:

def should_override_action(self, primary_action, q_action, dx, dy):
    # Solo anular en situaciones específicas
    if primary_action == q_action:
        return False
    
    # Permitir anulación cuando está muy cerca del jugador
    if abs(dx) < 50 and abs(dy) < 50:
        return True
    
    return False

Tipos de Comportamiento de Enemigos Enemy Behavior Types

Enemigos Barril Barrel Enemies

Características: Characteristics:

Estados de Comportamiento: Behavior States:

  1. Rodamiento: Movimiento horizontal normal Rolling: Normal horizontal movement
  2. Detección de Bordes: Identifica límites de plataforma Edge Detection: Identifies platform boundaries
  3. Navegación de Plataformas: Salta entre plataformas Platform Navigation: Jumps between platforms
  4. Persecución del Jugador: Persigue activamente al jugador Player Pursuit: Actively chases the player

Enemigos Monstruo Monster Enemies

Características: Characteristics:

Estados de Comportamiento: Behavior States:

1. Estado de Caída
   # Cae del cielo por 5-8 segundos
   duration = random.randint(300, 480)  # frames
   velocity_x = 0  # Sin movimiento horizontal

2. Estado de Espera
   # Se queda quieto por 1-2 segundos
   duration = random.randint(60, 120)  # frames
   velocity_x = 0
   # Indicador visual: círculo amarillo

3. Estado de Caza
   # Persigue activamente al jugador
   if abs(dx) > 10:
       direction = 1 if dx > 0 else -1
       velocity_x = speed * direction
   
   # Saltar si el jugador está arriba
   if dy < -40 and abs(dx) < 60:
       velocity_y = -101. Falling State
   # Falls from sky for 5-8 seconds
   duration = random.randint(300, 480)  # frames
   velocity_x = 0  # No horizontal movement

2. Waiting State
   # Stays still for 1-2 seconds
   duration = random.randint(60, 120)  # frames
   velocity_x = 0
   # Visual indicator: yellow circle

3. Hunting State
   # Actively pursues the player
   if abs(dx) > 10:
       direction = 1 if dx > 0 else -1
       velocity_x = speed * direction
   
   # Jump if player is above
   if dy < -40 and abs(dx) < 60:
       velocity_y = -10

Características Avanzadas de IA Advanced AI Features

Sistema de Pausa Adaptativo Adaptive Pause System

Los enemigos implementan un sistema de pausa dinámico: Enemies implement a dynamic pause system:

# Pausa inicial: 1 segundo cada 5 segundos
pause_duration = 60      # frames (1 segundo)
pause_cycle = 300        # frames (5 segundos)
pause_reduction = 5      # frames a reducir cada vez

# Cada pausa se vuelve más corta
new_duration = max(10, pause_duration - pause_reduction)# Initial pause: 1 second every 5 seconds
pause_duration = 60      # frames (1 second)
pause_cycle = 300        # frames (5 seconds)
pause_reduction = 5      # frames to reduce each time

# Each pause becomes shorter
new_duration = max(10, pause_duration - pause_reduction)

Inteligencia de Navegación de Plataformas Platform Navigation Intelligence

La IA puede navegar inteligentemente entre plataformas: The AI can intelligently navigate between platforms:

def should_actively_drop(self, current_platform, player_platform):
    # Caer si el jugador está en plataforma inferior
    if player_platform.top > current_platform.top:
        return True
    
    # Caer si está en el borde de la plataforma
    if at_platform_edge():
        return True
    
    return False# Drop if player is on lower platform
    if player_platform.top > current_platform.top:
        return True
    
    # Drop if at platform edge
    if at_platform_edge():
        return True
    
    return False

Optimización de Rendimiento Performance Optimization

Normalización del Espacio de Estados State Space Normalization

Todos los valores de estado se normalizan al rango [0,1] para un mejor aprendizaje: All state values are normalized to [0,1] range for better learning:

normalized_x = x_position / window_width
normalized_y = y_position / window_height

Exploración Epsilon-Greedy Epsilon-Greedy Exploration

Equilibra exploración vs explotación: Balances exploration vs exploitation:

if random.random() < epsilon:
    action = random.choice(available_actions)  # Explorar
else:
    action = argmax(Q_values)  # Explotaraction = random.choice(available_actions)  # Explore
else:
    action = argmax(Q_values)  # Exploit

Parámetros de Ajuste Tuning Parameters

Tasa de Aprendizaje (α = 0.1) Learning Rate (α = 0.1)

Factor de Descuento (γ = 0.95) Discount Factor (γ = 0.95)

Tasa de Exploración (ε = 0.2) Exploration Rate (ε = 0.2)

Conclusión Conclusion

Este sistema de IA crea enemigos desafiantes y adaptativos que proporcionan una experiencia de juego atractiva mientras mantienen la sensación clásica de Donkey Kong. La combinación de lógica basada en reglas con Q-Learning resulta en comportamientos que son tanto predecibles como sorprendentes. This AI system creates challenging and adaptive enemies that provide an engaging gaming experience while maintaining the classic Donkey Kong feel. The combination of rule-based logic with Q-Learning results in behaviors that are both predictable and surprising.