- Physics Beats Hacks: Reinforcement Learning for Flappy Bird from First Principles
- Why This Project Exists
- Act I: First-Principles Physics Explains Every Failure
- Act II & III: Two Textbook Fixes (and a 2×2 Synergy)
- Main Results (10 Seeds Each, Auto-Generated from
results/runs_full.json) - Seeing Inside the Agent's Brain
- Clean 5-File Architecture (~760 Lines Total)
- Quick Start (1-Command Reproduction)
- Authors & References
- Load a Trained Agent Directly from Hugging Face
- Why This Project Exists
Physics Beats Hacks: Reinforcement Learning for Flappy Bird from First Principles
Why naive RL fails at Flappy Bird—and how two textbook fixes (no neural networks, pure NumPy, 5 clean files) jump from 1 pipe to 92% cap mastery and 215-pipe endurance.
Trained Tile-Coded $\text{SARSA}(\lambda)$ agent gliding through unseen pipes with a live motion trail (amber = flap, blue = coast) and real-time Flap-vs-Coast $Q$-advantage telemetry. Watch it fly live—or play against it—in your browser →
Why This Project Exists
Most RL demos either throw a giant neural network at a simple game or report a single tabular Q-learning score without explaining why anything worked or failed.
We started with a simple question (CS 654 Reinforcement Learning, Project 4): how do reward functions and state representations affect tabular RL in Flappy Bird? What we found was a chain of surprising failure modes—every single one explained by 5 lines of ballistics, and solved cleanly using classic Sutton & Barto theory (zero PyTorch, CPU-only).
Act I: First-Principles Physics Explains Every Failure
In our Gymnasium environment (FLAP_VEL = -9, GRAVITY = 1, GAP = 100, BIRD_R = 12):
- The 45 px Flap Trap (Why naive reward shaping collapses to 1.24 pipes): A single flap rises $\sum_{k=1}^{9} k = \mathbf{45\text{ px}}$ over 9 frames, while the safe clearance above the gap center is only $50 - 12 = \mathbf{38\text{ px}}$. Flapping at gap center ($\Delta y = 0$) smashes the top pipe on frame 6. The true safe flap window is strictly below center ($\Delta y \in [+7, +38]\text{ px}$). Naive shaping pays a per-frame bonus peaking at $\Delta y = 0$ (~+5.0/pipe vs. +1.0 for passing a pipe)—literally bribing the bird into a ceiling trap.
- The Silent Coasting Prior (Why random tie-breaking drops 33.7 → 2.7 pipes):
One flap lasts 19 frames, so optimal play coasts ~88% of the time. NumPy's default
argmax([0, 0]) = 0secretly gives unvisited states the prior "when unsure, coast." Random tie-breaking flaps 50% of the time and rockets straight into the ceiling. - Why Eligibility Traces Alone Fail (
Tabular Q(λ=0.85)= 0.01 pipes): Pushing a-1crash backward 20+ frames in a zero-initialized table makes $Q(\text{coast}) < 0 = Q(\text{flap})$ across dozens of isolated states at once—destroying the coasting prior and causing continuous ceiling-flapping! - The Curse of Dimensionality (Why 4D tabular collapses 33.7 → 0.53 pipes):
Physics shows steep consecutive drops require lookahead (
gap_after), yet adding that 4th feature explodes hard bins 4.7× (12.2k → 57.4k empty cells).
Act II & III: Two Textbook Fixes (and a 2×2 Synergy)
Replacing isolated bins with asymmetric Tile Coding (8 overlapping shifted grids in pure NumPy, Sutton & Barto Ch. 9.5.4) and adding replacing eligibility traces ($\lambda = 0.85$, Ch. 12.7) produces a clean 2×2 synergy—with 2.5× fewer training episodes (2,000 vs. 5,000) and 3× fewer parameters (4.0k vs. 12.2k):
- Generalization alone (
Tile SARSA(λ=0)): jumps from 33.72 → 54.13 pipes (82% cap hits), doubles endurance (50.6 → 113.2), and rescues Expanded 4D by 95× (0.53 → 50.65). - Generalization + Credit Assignment (
Tile SARSA(λ=0.85)): hits 57.27 / 59 pipes (92% cap hits) and 215.1 / 299 endurance—4.25× Tabular Q's endurance and 2.65× the hand-coded physics heuristic (81.2), reaching 10 pipes 4.75× faster (500 vs. 2,375 episodes). - On-Policy vs. Off-Policy (
Tile SARSA(λ)vs.Tile Q(λ)on 4D): On-policy $\text{SARSA}(\lambda)$ never cuts traces during early exploration, outscoring $Q(\lambda)$ on the 59-pipe benchmark (56.36 vs. 54.05), while both fly comfortably ~25.5 px clear of pipe walls (vs. 22.6 px for the heuristic).
Main Results (10 Seeds Each, Auto-Generated from results/runs_full.json)
Every number below is evaluated greedily on the same 20 unseen levels (seeds 10,000–10,019, cap 59 pipes) and 20 unseen endurance levels (seeds 20,000–20,019, cap 299 pipes). All Tile-Coded improvements over the Tabular Q baseline are statistically significant ($p < 0.001$, Welch's t-test & Mann–Whitney U, Cohen's $d \in [+2.31, +3.51]$).
| Act | Configuration | Train Eps | Pipes (Cap 59) [95% CI] | IQM | Cap Hits | Endurance (Cap 299) | Wall Margin | Ep to 10 | Non-Zero Params |
|---|---|---|---|---|---|---|---|---|---|
| Act 1 | Tabular Q (Sparse, 3D) (Baseline) | 5,000 | 33.72 [27.0, 40.4] | 34.5 | 27% | 50.6 | 25.9 px | 2,375 | 12.2k |
| Act 1 | Tabular Q (Naive Shaped, 3D) | 5,000 | 1.24 [1.0, 1.5] | 1.3 | 0% | 1.3 | 23.1 px | — | 11.1k |
| Act 1 | Tabular Q (PBRS, 3D) | 5,000 | 9.05 [6.6, 11.5] | 8.5 | 0% | 7.8 | 24.4 px | — | 9.1k |
| Act 1 | Tabular Q (Random Ties, 3D) | 5,000 | 2.73 [1.5, 4.0] | 2.4 | 0% | 2.6 | 24.8 px | — | 7.7k |
| Act 1 | Tabular Q (Expanded 4D) | 5,000 | 0.53 [0.4, 0.7] | 0.5 | 0% | 0.5 | 25.6 px | — | 57.4k |
| Act 1 | Tabular Q(λ=0.85) (3D) | 5,000 | 0.01 [0.0, 0.0] | 0.0 | 0% | 0.0 | 17.0 px | — | 8.4k |
| Act 2 | Tile SARSA(λ=0) (Basic 3D) | 2,000 | 54.13 [52.2, 56.1] | 54.2 | 82% | 113.2 | 25.2 px | 600 | 3.9k |
| Act 2 | Tile SARSA(λ=0) (Expanded 4D) | 2,000 | 50.65 [47.5, 53.8] | 50.6 | 68% | 83.3 | 25.4 px | 700 | 14.3k |
| Act 2 | Tile SARSA(λ=0.85) (Basic 3D) | 2,000 | 57.27 [56.1, 58.4] | 57.4 | 92% | 215.1 | 25.1 px | 500 | 4.0k |
| Act 2 | Tile SARSA(λ=0.85) (Expanded 4D) | 2,000 | 56.36 [54.3, 58.5] | 57.0 | 87% | 198.9 | 25.5 px | 600 | 15.0k |
| Act 3 | Tile Q(λ=0.85) (Expanded 4D) | 2,000 | 54.05 [50.5, 57.7] | 55.5 | 82% | 213.9 | 25.6 px | 500 | 14.5k |
| Ref | Hand-Coded Physics Heuristic | — | 45.40 | — | 50% | 81.2 | 22.6 px | — | 0 |
Seeing Inside the Agent's Brain
Plotting the learned greedy policy in $(\Delta y, v)$ space shows the AI **discovering the exact physics boundary $\Delta y = +7\text{ px}$**—never flapping above the ceiling limit and flaring smoothly only when falling into the lower safe band:
And watching a single agent evolve on the exact same unseen level (seed = 10,000):
Clean 5-File Architecture (~760 Lines Total)
Built in the CleanRL spirit—flat, readable, zero wrapper bloat:
| File | Responsibility |
|---|---|
env.py |
Custom Gymnasium FlappyBirdEnv (low[2]=-12 fixed), sparse/shaped/pbrs rewards, Pygame HUD renderer |
agents.py |
TabularAgent (Q-learning, SARSA, Watkins's $Q(\lambda)$, $\text{SARSA}(\lambda)$) + pure-NumPy TileCodingAgent |
run.py |
Frozen evaluation harness (10,000–10,019 Cap 59 + 20,000–20,019 Cap 299), parallel multi-seed runner |
analyze.py |
Computes IQM, 95% CIs, Welch/Mann–Whitney p-values, Cohen's d → emits TSV, Markdown, and LaTeX tables |
viz.py |
Regenerates all 4 vector PDF/PNG figures and figures/hero_demo.gif directly from results/runs_full.json |
Quick Start (1-Command Reproduction)
pip install -r requirements.txt
# 1. Fast sanity check (~1s): Gymnasium check_env + 50-episode smoke test
python run.py --mode smoke --workers 1
# 2. Full 10-seed benchmark (110 runs + endurance + saved seed-0 models)
python run.py --mode full --workers 16
# 3. Regenerate every statistic, table, vector PDF, PNG, and hero GIF from raw JSON
python analyze.py && python viz.py
Authors & References
Team: Brian Porter, Vinayaka Hegde, Sanjana Sasmal, Preston Huynh (CS 654 Reinforcement Learning, Project 4)
License: MIT
- Sutton & Barto, Reinforcement Learning: An Introduction (2nd ed., 2018) — Ch. 6 (TD Control), Ch. 9.5.4 (Tile Coding), Ch. 12 (Eligibility Traces).
- Ng, Harada & Russell, Policy Invariance Under Reward Transformations, ICML 1999.
- Henderson et al., Deep Reinforcement Learning that Matters, AAAI 2018.
- Agarwal et al., Deep RL at the Edge of the Statistical Precipice, NeurIPS 2021 (IQM & CIs).
Load a Trained Agent Directly from Hugging Face
from huggingface_hub import hf_hub_download
from agents import TileCodingAgent
from env import FlappyBirdEnv
ckpt = hf_hub_download("v1nayh3g/flappy-rl-first-principles", "models/tile_sarsa_3d_seed0.pkl")
agent = TileCodingAgent.load(ckpt)
env = FlappyBirdEnv(render_mode="human")
obs, _ = env.reset(seed=10_000)
done = False
while not done:
obs, _, term, trunc, info = env.step(agent.act(obs, eps=0.0))
done = term or trunc
print("Pipes passed:", info["score"])