Multi-Agent Reinforcement Learning & Self-Play Sandboxes

โš”๏ธ Multi-Agent Reinforcement Learning (MARL) & Self-Play Sandboxes

In game AI research (like DeepMindโ€™s AlphaStar or OpenAIโ€™s Dota 2 / Hide and Seek), artificial intelligence is not trained on fixed target datasets. Instead, two or more autonomous neural networks are placed inside a shared simulation sandbox to compete, cooperate, and co-evolve strategies through Self-Play and Multi-Agent Reinforcement Learning (MARL).


๐Ÿ›๏ธ The Competitive Self-Play Architecture

+-------------------------------------------------------------+
|               Shared Sandbox Arena (Godot 4)                |
|   - 3D Arena, Collisions, Raycast Sensors, Health, Damage    |
+-------------------------------------------------------------+
         โ”‚ (State s_t^A)                     โ”‚ (State s_t^B)
         โ–ผ                                   โ–ผ
+-----------------------+           +-----------------------+
|  Agent A Policy (ฯ€_A) |           |  Agent B Policy (ฯ€_B) |
|  (Red Fighter Net)    |           |  (Blue Fighter Net)   |
+-----------------------+           +-----------------------+
         โ”‚ (Action a_t^A)                    โ”‚ (Action a_t^B)
         โ”‚ [Move, Attack, Shield]            โ”‚ [Move, Attack, Shield]
         โ–ผ                                   โ–ผ
+-------------------------------------------------------------+
|                     Environment Update                      |
|   - Resolve Hits, Update HP, Calculate Zero-Sum Rewards     |
|   - Reward A = +1.0 (Hit), -1.0 (Damaged), +10.0 (Win)      |
|   - Reward B = -Reward A (Zero-Sum Dynamics)                |
+-------------------------------------------------------------+

๐ŸŒ€ 1. The Self-Play Dilemma: Non-Stationarity & "Spinning Tops"

When Agent A learns, Agent B's environment changes; when Agent B adapts, Agent A's environment changes. This creates a non-stationary moving target where agents can fall into Policy Cycling (e.g., A beats B with shields โ†’ B learns heavy attacks โ†’ A learns dodging โ†’ B forgets heavy attacks and reverts).

Solutions for Robust Self-Play:

  1. Fictitious Self-Play / League Training: Instead of only playing against the latest version of the opponent, agents play against a frozen Historical Snapshot Pool of past versions (70% latest opponent, 30% random past checkpoints).
  2. Asymmetric Spawns & Domain Randomization: Randomize arena obstacles, weapon spawn locations, movement speeds (ยฑ10%), and sensor noise so agents learn generalized combat tactics rather than overfitting to fixed coordinates.

๐ŸŽฎ 2. Setting Up the Godot 4 Sandbox Arena (ArenaCombat.gd)

In Godot 4, the arena environment manages simulation speed, agent resets, raycast sensory perception, and step ticks:

# ArenaManager.gd - Godot 4 Combat Sandbox
extends Node3D

@export var max_episode_steps: int = 1200
var current_step: int = 0

@onready var agent_red: CombatAgent = $AgentRed
@onready var agent_blue: CombatAgent = $AgentBlue

func _ready() -> void:
    # Set physics engine to maximum speed during training
    Engine.physics_ticks_per_second = 60
    Engine.time_scale = 10.0 # 10x fast-forward simulation
    reset_arena()

func reset_arena() -> void:
    current_step = 0
    agent_red.reset_agent(Vector3(-10, 0, 0), Vector3.RIGHT)
    agent_blue.reset_agent(Vector3(10, 0, 0), Vector3.LEFT)

func _physics_process(delta: float) -> void:
    current_step += 1
    
    # Check win/loss/timeout conditions
    if agent_red.health <= 0 or agent_blue.health <= 0 or current_step >= max_episode_steps:
        _evaluate_match_rewards()
        reset_arena()

func _evaluate_match_rewards() -> void:
    if agent_red.health > agent_blue.health:
        agent_red.give_reward(+10.0) # Win
        agent_blue.give_reward(-10.0) # Loss
    elif agent_blue.health > agent_red.health:
        agent_red.give_reward(-10.0)
        agent_blue.give_reward(+10.0)

๐Ÿ“ก 3. Sensory Vector Design (What the Combat AI Sees)

Each agentโ€™s observation vector (State St) must be expressed in Agent-Local Relative Space so strategies work from any arena angle:

                  [ Forward Ray 0ยฐ: Dist = 12.4m, Hit = Enemy ]
                                      \ | /
  [ Left Ray -30ยฐ: Dist = 4.2m ] โ”€โ”€โ”€ (Agent) โ”€โ”€โ”€ [ Right Ray +30ยฐ: Dist = 8.1m ]
                                      / | \

The 16-Float Observation Vector:

  1. health_ratio: HPcurrent/HPmaxโˆˆ[0.0,1.0]
  2. opponent_health_ratio: HPenemy/HPmaxโˆˆ[0.0,1.0]
  3. relative_enemy_x, relative_enemy_z: Normalized distance vector to opponent.
  4. enemy_facing_angle: Relative yaw angle to opponent (am I behind them?).
  5. current_speed: Normalized velocity magnitude.
  6. attack_cooldown_remaining: [0.0,1.0].
  7. raycasts[0..7]: 8 radial raycasts detecting distance to walls and obstacles.
  8. raycast_hit_types[0..7]: Discrete flags (0=Empty,1=Wall,2=Enemy).

๐Ÿ’ป 4. Competitive Centralized Critic (MAPPO in PyTorch)

In Multi-Agent PPO (MAPPO), each agent has its own private Actor (Policy) network for execution, but during training, the Critic (Value) network evaluates the full global arena state:

import torch
import torch.nn as nn
from torch.distributions import Categorical

# 1. Decentralized Actor Network (Runs inside Godot agent)
class CombatActor(nn.Module):
    def __init__(self, observation_dim: int = 24, action_dim: int = 5):
        super().__init__()
        # Actions: 0=Idle, 1=Move Forward, 2=Turn Left, 3=Turn Right, 4=Attack
        self.net = nn.Sequential(
            nn.Linear(observation_dim, 128),
            nn.Tanh(),
            nn.Linear(128, 128),
            nn.Tanh(),
            nn.Linear(128, action_dim) # Action logits
        )

    def forward(self, obs: torch.Tensor):
        logits = self.net(obs)
        dist = Categorical(logits=logits)
        action = dist.sample()
        return action, dist.log_prob(action)

# 2. Centralized Critic Network (Used only during offline training)
class CentralizedCombatCritic(nn.Module):
    def __init__(self, full_state_dim: int = 48): # Receives Red AND Blue observations
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(full_state_dim, 256),
            nn.ELU(),
            nn.Linear(256, 128),
            nn.ELU(),
            nn.Linear(128, 1) # Estimated expected match outcome value V(s)
        )

    def forward(self, full_state: torch.Tensor) -> torch.Tensor:
        return self.net(full_state)

๐Ÿ† 5. Reward Shaping: Avoiding Degenerate Behaviors

A common failure in combat sandbox research is Reward Exploitation (e.g., both agents learn that running into corners and doing nothing guarantees neither loses health):

Goal Naive Reward (Broken) Shaped Reward (Working)
Encourage Combat +1.0 per frame alive โ†’ Agents run away and camp forever โˆ’0.01 per frame alive (Time penalty) +Damage Dealt
Encourage Engagement +10.0 for winning โ†’ Zero gradient until someone accidentally dies +0.05ร—(Distance Decreased to Opponent)
Aiming Discipline +1.0 per attack โ†’ Agents spam attack key endlessly in empty air +2.0 on hit, โˆ’0.2 on missed attack whiff