Skip to content

Latest commit

 

History

History
292 lines (214 loc) · 7.72 KB

README.md

File metadata and controls

292 lines (214 loc) · 7.72 KB

Rocket League RL — Single Bot PPO Training

A complete Proximal Policy Optimization (PPO) reinforcement learning pipeline that trains one bot to score goals in a simplified 2D Rocket League–style environment. Designed to later connect to a Unity 3D game.


Architecture

ONE PPO AGENT  →  ONE CAR  →  ONE BALL  →  ONE GOAL

There is no opponent, no self-play, no multi-agent training.


Project Structure

rocket_league_rl/
├── environment/
│   ├── __init__.py
│   ├── physics.py          # 2D physics (car, ball, collision, boundaries)
│   └── rocket_env.py       # Gymnasium environment (RocketLeagueEnv)
├── agent/
│   ├── __init__.py          # Device selection (CUDA → MPS → CPU)
│   ├── network.py           # Actor-Critic with tanh-squashed Gaussian
│   ├── rollout.py           # Rollout buffer
│   ├── gae.py               # Generalized Advantage Estimation
│   └── ppo.py               # PPO agent (manual implementation)
├── training/
│   ├── __init__.py
│   ├── train.py             # Training loop with TensorBoard
│   └── evaluate.py          # Evaluation script
├── visualization/
│   ├── __init__.py
│   └── visualize.py         # Pygame visualization
├── models/                  # Saved checkpoints
├── logs/                    # TensorBoard logs
├── tests/
│   ├── __init__.py
│   ├── test_environment.py
│   ├── test_network.py
│   ├── test_rollout.py
│   ├── test_gae.py
│   └── test_ppo.py
├── requirements.txt
├── .gitignore
└── README.md

Environment

Field

A 2D rectangular field from (-10, -6) to (10, 6).

  • Car starts near x = -8 with a small random y offset.
  • Ball is randomised around the centre-left portion of the field.
  • Goal is a vertical region at x = 10, spanning y ∈ [-2, 2].

Observation Space (11 dimensions)

Index Feature
0 car x
1 car y
2 car velocity x
3 car velocity y
4 car angle
5 ball x
6 ball y
7 ball vx
8 ball vy
9 goal x
10 goal y

Action Space (2 continuous)

Index Action Range
0 steering [-1, 1]
1 throttle [-1, 1]

Physics

  • Car: accelerates in facing direction, turns via steering, has friction and max speed.
  • Ball: moves with velocity, decelerates through friction, bounces off walls.
  • Collision: when the car touches the ball, an impulse is applied in the car→ball direction. Faster cars kick harder.

Reward Function

The reward is carefully shaped so the bot can learn the full sequence:

Component Signal Scale
Ball→goal distance Δ Positive when ball moves closer to goal ×5.0
Car→ball distance Δ Positive when car moves closer to ball ×1.0
Hit bonus One-time reward when car contacts ball +1.0
Ball direction Cosine similarity of ball velocity with ball→goal vector ×0.5
Goal scored Large reward when ball enters the goal region +10.0
Time penalty Small negative each step -0.01

Episode Handling

  • Terminated when the ball enters the goal (bot scores).
  • Truncated after 500 steps (configurable).
  • On termination or truncation the environment resets.

Actor-Critic Network

obs (11) → Linear(128) → Tanh → Linear(128) → Tanh
                                      ↓            ↓
                                 Actor head    Critic head
                                  mean (2)      value (1)
                                log_std (2)

Tanh-Squashed Gaussian Policy

Actions are sampled from a Normal distribution and squashed through tanh so they are always in [-1, 1]. The log probability is corrected:

log π(a) = log N(u; μ, σ) − Σ log(1 − tanh²(u) + ε)

where u is the raw Gaussian sample and a = tanh(u).

During evaluation, the deterministic action is tanh(μ).

When re-evaluating stored actions in PPO, the raw action is recovered via a numerically stable atanh.


GAE (Generalized Advantage Estimation)

δ_t = r_t + γ V(s_{t+1}) (1 − done_t) − V(s_t)
Â_t = Σ (γλ)^l δ_{t+l}
  • γ = 0.99 (discount factor)
  • λ = 0.95 (GAE smoothing)
  • Computed backwards; episode boundaries reset the accumulation.
  • Returns = advantages + values (critic targets).

PPO (Proximal Policy Optimization)

Manually implemented — no RL library PPO is used.

Clipped Surrogate Objective

ratio = exp(new_log_prob − old_log_prob)
L_clip = min(ratio × Â, clip(ratio, 1±ε) × Â)

Total Loss

loss = −L_clip + 0.5 × value_loss − 0.01 × entropy

Hyperparameters

Parameter Default
Learning rate 3e-4
γ (gamma) 0.99
λ (GAE lambda) 0.95
Clip ratio ε 0.2
Value coefficient 0.5
Entropy coef. 0.01
Update epochs 10
Batch size 64
Max grad norm 0.5
Rollout length 2048

Usage

Install

python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

Train

python3 -m training.train --steps 10000      # quick test
python3 -m training.train --steps 100000     # moderate training
python3 -m training.train --steps 500000     # longer training
python3 -m training.train --steps 1000000    # extended training

Resume from checkpoint:

python3 -m training.train --steps 100000 --resume

Evaluate

python3 -m training.evaluate
python3 -m training.evaluate --episodes 50

Visualize

python3 -m visualization.visualize
python3 -m visualization.visualize --manual   # keyboard control for debugging

TensorBoard

tensorboard --logdir logs

Run Tests

python3 -m tests.test_environment
python3 -m tests.test_network
python3 -m tests.test_rollout
python3 -m tests.test_gae
python3 -m tests.test_ppo

macOS / Apple Silicon

The project automatically detects MPS (Metal Performance Shaders) on Apple Silicon and uses it for GPU acceleration. Falls back to CPU if unavailable. No NVIDIA GPU required.


Model Saving

The trained model is saved to models/rocket_league_ppo.pt and includes:

  • Network weights
  • Optimizer state (for resume)
  • Observation and action dimensions
  • All hyperparameters

Future: Unity Integration

The PPO agent is deliberately separated from the physics engine. A Unity environment can replace RocketLeagueEnv by providing the same Gymnasium-compatible interface:

  • reset() → (observation, info)
  • step(action) → (observation, reward, terminated, truncated, info)

The action space remains (steering, throttle) ∈ [-1, 1]².


Technology Stack

  • Python 3.11
  • PyTorch — neural network, optimisation
  • Gymnasium — environment API
  • NumPy — numerical computation
  • Pygame — visualization
  • Matplotlib — plotting (optional)
  • TensorBoard — training metrics
  • Stable-Baselines3 — available for future benchmarking (not used for PPO)