Skip to content

Latest commit

 

History

History
258 lines (228 loc) · 16 KB

File metadata and controls

258 lines (228 loc) · 16 KB

PongAI Architecture Diagram

System Overview

┌──────────────────────────────────────────────────────────────────────────────┐
│                           PongAI PROJECT ARCHITECTURE                        │
└──────────────────────────────────────────────────────────────────────────────┘


     ┌─────────────────────────────────────────────────────────────────┐
     │                         CONFIGURATION LAYER                     │
     │                                                                 │
     │  config.py          - Central constants & settings             │
     │  utils.py           - Helper functions & utilities             │
     │  main.py            - CLI entry point with subcommands         │
     │                                                                 │
     └─────────────────────────────────────────────────────────────────┘
                                       ▲
                   ┌───────────────────┼───────────────────┐
                   │                   │                   │
                   ▼                   ▼                   ▼
     
     ┌──────────────────────┐  ┌──────────────────────┐  ┌──────────────────────┐
     │   PHYSICS LAYER      │  │   RL TRAINING       │  │   DEMO LAYER         │
     │   (engine/)          │  │   (train/, rl/)     │  │   (demo/)            │
     │                      │  │                      │  │                      │
     │  engine/pong.py      │  │  train/ppo.py       │  │  demo/play.py        │
     │                      │  │  ├─ PPO agent       │  │  ├─ PyGame UI        │
     │  Classes:            │  │  ├─ Checkpoints     │  │  ├─ User input      │
     │  ├─ Paddle           │  │  └─ TensorBoard     │  │  ├─ AI inference    │
     │  ├─ Ball             │  │                      │  │  └─ Rendering      │
     │  └─ PongEngine       │  │  rl/env.py          │  │                      │
     │                      │  │  ├─ Observations    │  │  Models:             │
     │  Functions:          │  │  ├─ Rewards         │  │  • Novice (50k)     │
     │  ├─ Collision        │  │  └─ Opponent AI     │  │  • Intermediate     │
     │  ├─ Physics          │  │                      │  │  • Advanced (500k)  │
     │  └─ Scoring          │  │  Vectorization:     │  │  • Master (1M)      │
     │                      │  │  • DummyVecEnv      │  │                      │
     │  Pure Math!          │  │  • SubprocVecEnv    │  │  Dynamic Swapping!   │
     │  (No Dependencies)   │  │  • Multiprocessing  │  │  (Press 1-4 to      │
     │                      │  │                      │  │   change difficulty) │
     │                      │  │                      │  │                      │
     └──────────────────────┘  └──────────────────────┘  └──────────────────────┘
              ▲                          ▲                          ▲
              │                          │                          │
              └──────────────┬───────────┴───────────────┬──────────┘
                             │                          │
                             ▼                          ▼
              ┌──────────────────────┐    ┌──────────────────────┐
              │   DATA FLOW          │    │   API LAYER          │
              │                      │    │   (api/)             │
              │  state dict          │    │                      │
              │    ↓                 │    │  api/app.py          │
              │  normalize            │    │  ├─ FastAPI         │
              │    ↓                 │    │  ├─ WebSocket       │
              │  observation         │    │  ├─ Broadcast       │
              │    ↓                 │    │  └─ CORS Config     │
              │  PPO predict          │    │                      │
              │    ↓                 │    │  Endpoints:          │
              │  action              │    │  • GET /             │
              │                      │    │  • GET /health       │
              │  Deterministic!      │    │  • WS /ws/game-data  │
              │  (consistency)       │    │  • POST /broadcast   │
              │                      │    │  • GET /clients      │
              └──────────────────────┘    └──────────────────────┘


     ┌──────────────────────────────────────────────────────────────────┐
     │                    TRAINING WORKFLOW                             │
     │                                                                  │
     │   1. CustomPongEnv wraps PongEngine                             │
     │   2. DummyVecEnv / SubprocVecEnv parallelizes environments      │
     │   3. PPO learns policy via gradient ascent                      │
     │   4. CheckpointCallback saves every 50k steps                   │
     │   5. TensorBoard tracks learning curves                         │
     │                                                                  │
     │   Models saved to: models/rl_model_XXXX_steps.zip               │
     │                                                                  │
     └──────────────────────────────────────────────────────────────────┘


     ┌──────────────────────────────────────────────────────────────────┐
     │                      DEMO WORKFLOW                               │
     │                                                                  │
     │   60 FPS Game Loop:                                             │
     │                                                                  │
     │   1. PyGame event handling (keyboard input, window events)      │
     │   2. Extract actions:                                           │
     │      • Human action from W/S keys → action_left                │
     │      • AI action from loaded model → action_right              │
     │   3. Engine.step(action_left, action_right)                     │
     │      → returns new state, scoring flags                         │
     │   4. Normalize state for model inference                        │
     │   5. Call model.predict(state, deterministic=True)             │
     │   6. PyGame rendering (paddles, ball, score, UI)               │
     │   7. Clock.tick(60) for FPS control                             │
     │                                                                  │
     │   Dynamic Model Loading:                                        │
     │   • Press 1: Load Novice (50k)                                  │
     │   • Press 2: Load Intermediate (200k)                           │
     │   • Press 3: Load Advanced (500k)                               │
     │   • Press 4: Load Master (1M)                                   │
     │   → Model swapped instantly, game continues                     │
     │                                                                  │
     └──────────────────────────────────────────────────────────────────┘


                            MODULE DEPENDENCIES


                                    ┌─────────────────┐
                                    │  Requirements   │
                                    │                 │
                                    │ • pygame        │
                                    │ • gymnasium     │
                                    │ • stable-bases3 │
                                    │ • fastapi       │
                                    │ • uvicorn       │
                                    │ • websockets    │
                                    │ • numpy         │
                                    └────────┬────────┘
                                             │
                    ┌────────────────────────┼────────────────────────┐
                    │                        │                        │
                    ▼                        ▼                        ▼
        ┌─────────────────────┐  ┌──────────────────────┐  ┌──────────────────┐
        │   engine/pong.py    │  │   rl/env.py          │  │  demo/play.py    │
        │                     │  │                      │  │                  │
        │ Imports:            │  │ Imports:             │  │ Imports:         │
        │ • numpy             │  │ • gymnasium          │  │ • pygame         │
        │ (minimal!)          │  │ • numpy              │  │ • numpy          │
        │                     │  │ • engine/pong        │  │ • stable-bases3  │
        │ Pure math,          │  │                      │  │ • engine/pong    │
        │ NO pygame           │  │ Wraps PongEngine     │  │ • rl/env         │
        └─────────────────────┘  │ for RL training      │  │                  │
                                 └──────────────────────┘  │ Renders & runs   │
                                                           │ live game        │
                                                           └──────────────────┘
                                              │
                                              ▼
                        ┌─────────────────────────────────────┐
                        │     train/ppo.py                    │
                        │                                     │
                        │ Uses: stable-baselines3             │
                        │ Creates: DummyVecEnv/SubprocVecEnv │
                        │ Trains: PPO agent                   │
                        │ Saves: Model checkpoints            │
                        │ Logs: TensorBoard metrics           │
                        └──────────────┬──────────────────────┘
                                       │
                                       ▼
                        ┌─────────────────────────────────────┐
                        │     api/app.py                      │
                        │                                     │
                        │ Uses: FastAPI, uvicorn, websockets  │
                        │ Streams: Game state via WS          │
                        │ Handles: Dashboard connections     │
                        └─────────────────────────────────────┘


                          DIRECTORY TREE


PongAI/
├── engine/           ← Physics & collision math
│   ├── __init__.py
│   └── pong.py       (350+ lines)
│
├── rl/               ← Gymnasium environment wrapper  
│   ├── __init__.py
│   └── env.py        (250+ lines)
│
├── train/            ← Training orchestration
│   ├── __init__.py
│   └── ppo.py        (150+ lines)
│
├── demo/             ← Interactive demo application
│   ├── __init__.py
│   └── play.py       (400+ lines)
│
├── api/              ← FastAPI WebSocket server
│   ├── __init__.py
│   └── app.py        (250+ lines)
│
├── models/           ← Generated: trained models
├── pong_tensorboard/ ← Generated: training logs
│
├── __init__.py       ← Package root
├── config.py         ← Configuration & constants (80+ lines)
├── utils.py          ← Helper functions (80+ lines)
├── main.py           ← CLI entry point (120+ lines)
├── setup.py          ← Project setup & validation (180+ lines)
│
├── requirements.txt  ← Dependencies
├── .gitignore        ← Git ignore rules
│
├── README.md         ← Full documentation (700+ lines)
├── QUICKREF.md       ← Quick reference guide  
├── IMPLEMENTATION.md ← Technical details
├── SCAFFOLD_SUMMARY.txt ← This summary
└── ARCHITECTURE.md    ← This file


                        COMPONENT INTERACTIONS


  Training Time:
  ──────────────
  
  CustomPongEnv ←→ PongEngine
       ↓
  normalize observations to [-1, 1]
       ↓
  PPO Agent (learns policy)
       ↓
  Save checkpoint every 50k steps
       ↓
  TensorBoard logs metrics


  Demo Time:
  ─────────
  
  PyGame Input (W/S) ──→ Action
                           ↓
                      PongEngine (step)
                           ↓
  ┌─ Raw State
  │    ↓
  └─ Normalize to [-1, 1]
       ↓
  Load Model (1-4 key handling)
       ↓
  PPO.predict(state, deterministic=True)
       ↓
  Execute AI Action
       ↓
  Render (pygame.draw)


  API Time (Optional):
  ───────────────────
  
  Demo broadcasts game state
       ↓
  WebSocket /ws/game-data
       ↓
  FastAPI ConnectionManager
       ↓
  Broadcast to all connected clients
       ↓
  Web Dashboard receives updates


═══════════════════════════════════════════════════════════════════════════════
Generated: April 6, 2026
Status: Production Ready ✅