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
Solutions for Robust Self-Play:
- 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 (
latest opponent, random past checkpoints). - Asymmetric Spawns & Domain Randomization: Randomize arena obstacles, weapon spawn locations, movement speeds (
), 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
[ 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:
health_ratio:opponent_health_ratio:relative_enemy_x, relative_enemy_z: Normalized distance vector to opponent.enemy_facing_angle: Relative yaw angle to opponent (am I behind them?).current_speed: Normalized velocity magnitude.attack_cooldown_remaining:. raycasts[0..7]: 8 radial raycasts detecting distance to walls and obstacles.raycast_hit_types[0..7]: Discrete flags ().
๐ป 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 | ||
| Encourage Engagement | ||
| Aiming Discipline |
๐ Related Notes
- Evolutionary Algorithms & Genetic Neural Nets โ Evolving neural networks without backpropagation via mutations.
- Sensory Perception & Spatial Grids for AI โ Raycast grids, spatial awareness, and memory buffers for game agents.
- Reinforcement Learning & Game AI โ Single-agent DQN and PPO fundamentals.
- ONNX & Engine Inference (Unreal & Godot) โ Running trained combat policies at 60fps in Godot.
- Machine Learning Hub โ Master machine learning index.
- Game Development Hub โ Central game development index.