Reinforcement Learning & Game AI

🎮 Reinforcement Learning & Game AI (DQN, PPO & Gym)

Unlike traditional game AI built on finite state machines or behavior trees, Reinforcement Learning (RL) allows an autonomous AI agent to learn how to play complex 2D/3D games directly through trial, error, and rewards.

This approach mirrors the official Hugging Face Deep RL curriculum and OpenAI Gym / Gymnasium workflows.


🏛️ The Reinforcement Learning Feedback Loop

+-------------------------------------------------------------+
|                      Environment (Game)                     |
|         (Godot / Unreal / Custom Engine / Gymnasium)        |
+-------------------------------------------------------------+
               ▲                               │
               │ Action (a_t)                  │ State Observation (s_t)
               │ (e.g. Move, Jump, Shoot)      │ Reward (r_t) (e.g. +10, -5)
               │                               ▼
+-------------------------------------------------------------+
|                      Agent (Neural Network)                 |
|         (Policy Network / Deep Q-Network in PyTorch)        |
+-------------------------------------------------------------+
  1. State / Observation (st): The sensory input the agent receives (e.g., player coordinates, raycast distance sensors, enemy positions, or raw pixel frames).
  2. Action (at): Discrete actions (e.g., 0=Idle, 1=Left, 2=Right, 3=Jump) or Continuous vectors (e.g., analog steering angle [−1.0,+1.0]).
  3. Reward (rt): A scalar feedback value designed by the developer (e.g., +1.0 for surviving a second, +100.0 for reaching goal, −50.0 for falling into a pit).
  4. Discount Factor (γ≈0.99): Balances immediate rewards against long-term future payoffs:
Rt=∑k=0∞γkrt+k

⚔️ DQN vs. PPO: Choosing the Right RL Algorithm

Feature Deep Q-Networks (DQN) Proximal Policy Optimization (PPO)
Action Space Discrete only (e.g. D-Pad buttons) Discrete & Continuous (e.g. Analog joystick, throttle)
Paradigm Value-Based: Learns the Q(s,a) expected return for every action and picks arg⁡maxaQ(s,a). Policy Gradient (Actor-Critic): Actor outputs action probabilities; Critic evaluates expected state value.
Stability Requires Replay Buffers and Target Networks to prevent divergence. Industry gold standard for stability; clips policy updates to prevent destructive weight updates.
Best Used For 2D retro games, grid puzzles, turn-based card combat. 3D physics bots, character ragdoll walking, self-driving cars, FPS combat.

💻 Building a Deep Q-Network (DQN) in PyTorch

Below is a complete PyTorch architecture for a Q-Network that receives raycast distance sensors and outputs optimal action scores:

import torch
import torch.nn as nn
import torch.nn.functional as F

class DQN(nn.Module):
    def __init__(self, observation_dim: int, action_dim: int):
        super().__init__()
        # Feature extractor layers
        self.fc1 = nn.Linear(observation_dim, 128)
        self.fc2 = nn.Linear(128, 128)
        self.fc3 = nn.Linear(128, 64)
        
        # Output layer: Returns estimated Q-value for EVERY possible action
        self.q_out = nn.Linear(64, action_dim)

    def forward(self, state: torch.Tensor) -> torch.Tensor:
        x = F.relu(self.fc1(state))
        x = F.relu(self.fc2(x))
        x = F.relu(self.fc3(x))
        return self.q_out(x)

    # Action selection with Epsilon-Greedy exploration
    def select_action(self, state: torch.Tensor, epsilon: float, action_dim: int) -> int:
        import random
        if random.random() < epsilon:
            return random.randrange(action_dim) # Explore: random exploratory action
        else:
            with torch.no_grad():
                q_values = self.forward(state)
                return q_values.argmax().item()  # Exploit: choose best known action

🛠️ The Experience Replay Buffer & Target Network

When training a DQN, sequential video game frames are heavily correlated. Feeding consecutive frames directly into a neural network breaks the standard statistical assumption of independent and identically distributed (i.i.d.) data.

To solve this:

  1. Experience Replay Buffer: Store transitions (st,at,rt,st+1,done) in a large circular memory buffer (e.g. 100,000 steps). Sample random mini-batches of 64 transitions during training.
  2. Target Network (Q^): Maintain a second copy of the model weights that updates slowly (every 1,000 steps). Calculate the Bellman loss against this frozen target to prevent moving-target feedback loops:
Loss=(r+γmaxa′Q^(s′,a′)−Q(s,a))2

🤖 Bridging PyTorch with Godot 4 & Unreal Engine

To train an agent inside your game engine:

  1. Godot RL Agents (Hugging Face / Open Source): A library that connects Godot 4 games with Python RL frameworks (Stable-Baselines3, Ray RLlib) over high-speed Shared Memory / WebSockets.
  2. Headless Engine Parallelization: Run 16 or 32 instances of your Godot/Unreal game simultaneously in headless (no-rendering) mode to collect millions of gameplay frames in minutes.
  3. ONNX Deployment: Once trained, export the policy to .onnx and execute it directly inside the engine with zero Python dependencies (see ONNX & Engine Inference (Unreal & Godot)).