In Part 1, we built a zero-cheating, blank-slate agent powered by gemini-decision-1 that cleared Levels 1 and 2 of 1989 Prince of Persia on a 700 MHz Raspberry Pi 1 (~450 ms p50, 0 output tokens, no vision, no memory writes).

That left an obvious systems question: can we remove the cloud LLM completely and train a tiny local neural network purely from game outcomes to beat the game offline?

Here are the headline numbers from this follow-up:

  • Zero LLMs, zero cloud API calls ($0): One single 21,665-parameter (198 KB JSON) recurrent Actor-Critic (PPO + GRU) model running in pure Python stdlib.
  • 30× faster inference: 13.2–16.1 ms p50 vs. 448 ms p50 for gemini-decision-1.
  • 24,506× simulation speedup: A custom frame-stepped Headless SDLPoP C library (libsdlpop_headless.so) running authentic 1989 physics at 294,075 ticks/sec in C (16,970 ticks/sec in full Python).
  • Verified clears (zero cheats, zero quicksaves, authentic 3-HP, blank-slate fog-of-war):
    • Headless SDLPoP: 9/9 (100%) across Levels 1–3 (0.34–0.67 s per level), and 11/12 (91.7%) across Levels 1–4 including Level 4’s Magic Mirror jump (0.0 avg deaths on Levels 1, 3, and 4).
    • Physical Raspberry Pi 1 (live hardware): Cleared Level 1 → Level 2 → Level 3 → Level 4 with 0 cloud API calls.

Below is the complete methodology — every architectural decision, feature, equation, sim-to-real failure mode, and honest generalization boundary.


1. Why Flat Pixel-to-Button RL Fails on 1989 Prince of Persia

Most open-source RL attempts on 1989 Prince of Persia (wrapping SDLPoP with 84×84 grayscale pixels and 5 discrete joystick actions) hit the same wall as Atari’s Montezuma’s Revenge. The game stacks two hard problems on top of each other:

  1. Long-horizon sparse-reward dungeon exploration: Opening an exit door often requires navigating 10–20 rooms, picking up a sword, backtracking past guards, pressing a switch 4 rooms away, and sprinting through a timed gate.
  2. Animation-locked, frame-precise motor control: Prince of Persia runs at 12 ticks/sec (83.3 ms/frame). Multi-frame running jumps, SHIFT ledge grabs, chomper openings, and sword parry-riposte windows punish a 1-frame timing slip with instant death.

We solve this by decomposing the agent into three cleanly separated layers:

Zero-LLM Three-Layer Loop (21,665-Param PPO + GRU) Headless x86 (1,700×–24,506×) & Live Pi 1 (1×)
Read-only room state 30 relational features Chosen room goal Authentic 1989 keys: LEFT, RIGHT, UP, DOWN, SHIFT 1989 SDLPoP Engine Headless 1,700× or Pi 1× 1. Blank-Slate Map Fog-of-War + legal goals 2. 198 KB RL Brain PPO + 32-dim GRU 3. Motor Skills walk, jump, climb, duel
  1. Blank-Slate Mental Map (SimpleFogMap): Starts empty every level, records discovered rooms, switches, dead ends, and fatal pits, and uses intra-room pathfinding to list only the 2–5 legal goals currently reachable.
  2. 198 KB RL Brain (PPO + GRU): Scores each legal goal using 30 relational features plus a 32-dim cross-room working memory — zero level IDs, zero room IDs, zero LLMs.
  3. Closed-Loop Motor Skills: Translates the chosen room goal (GO_LEFT, PRESS_BUTTON, FIGHT_GUARD) into authentic 1989 keyboard presses (LEFT, RIGHT, UP, DOWN, SHIFT).

Non-negotiable zero-cheating contract:

  • Read-only observation: On the Pi, /proc/<pid>/mem is read-only; in headless C, pop_get_state() is strictly read-only. Zero memory writes, zero full-level spoilers.
  • Blank-slate SimpleFogMap: Every evaluation run starts with an empty room graph and learns room connections strictly by walking through them.
  • Authentic 1989 rules: start_hitp = 3, have_sword_from_level = 2, --use_quicksave=False, control strictly via authentic keys (LEFT, RIGHT, UP, DOWN, SHIFT).

2. Building a 24,506× Headless SDLPoP C Training Engine

A single 160-step episode on the live Raspberry Pi takes ~11 minutes because 99.9% of each 83.3 ms game tick is spent sleeping in SDL_Delay() and rendering to HDMI. Training 500 RL episodes on live hardware would take nearly 4 days.

Because SDLPoP is open-source C, we compiled it into a shared library (headless/libsdlpop_headless.so) with zero edits to upstream game logic by using GNU linker symbol wrapping (-Wl,--wrap=SDL_Delay, -Wl,--wrap=update_screen, -Wl,--wrap=play_sound_from_buffer):

  • pop_init(data_dir): Initializes SDL_VIDEODRIVER=dummy, SDL_AUDIODRIVER=dummy, authentic LEVELS.DAT, and 1989 defaults (use_fixes_and_enhancements = 0).
  • pop_reset(level): Loads any level 1..14 cleanly in <0.1 ms with zero cutscenes.
  • pop_step(in_x, in_y, in_shift): Sets authentic keyboard inputs and executes exactly one play_frame() physics tick.
  • pop_get_state(out): Exports a packed C struct that our ctypes wrapper (headless/headless_env.py) maps into the exact same /state dictionary schema as our Raspberry Pi bridge.
  • pop_save_snapshot() / pop_load_snapshot(): Microsecond in-memory state snapshots for Go-Explore training (disabled during evaluation).

Measured Throughput Benchmark (10,000 Ticks)

Execution Mode Throughput Speedup vs. 12 Hz Real-Time Full Level 1 Clear
Live Raspberry Pi 1 (1×) 12 ticks/sec 1× ~492 s (~8 min)
Headless Python step() (full /state dict) 16,970 ticks/sec 1,414× 0.288 s
Headless Raw C step_raw_fast() 294,075 ticks/sec 24,506× —

A Fun Sim-to-Real Catch: Sprite Hitboxes

Our first headless build skipped loading PNG sprites to save time, which accidentally shrank Kid’s hitbox to 1 pixel wide because the 1989 collision engine measures hitbox width directly from the sprite image. Loading the real sprites once at startup added zero physics overhead and restored exact hitbox parity with the Raspberry Pi.


3. The 21,665-Parameter Zero-LLM Brain (ActorCriticPolicy)

To solve multi-room dungeons without any LLM teacher, we designed a compact relational Actor-Critic with Gated Working Memory (headless/ppo_policy.py) that runs identically in pure Python stdlib on both x86 and the Raspberry Pi 1.

Input Representation: 30 Relational Features per Candidate Goal

At every decision point s_t, intra-room Dijkstra exposes only the K_t ∈ {2..5} legal reachable goals A(s_t). Each candidate a_i ∈ A(s_t) is encoded into a 30-dimensional vector x_{t,i} ∈ R^{30}:

Group Dims Exact Features
Goal Type One-Hot 10 GO_LEFT, GO_RIGHT, GO_UP, GO_DOWN, PRESS_BUTTON, PICKUP_SWORD, DRINK_POTION, FIGHT_GUARD, ENTER_EXIT_DOOR, FLEE_GUARD
Local Fog-of-War 6 matches_bfs_target_dir, dst_is_unvisited, dst_visit_count_log, is_uturn, room_turns_norm, goal_is_blocked
Current Room State 8 have_sword, closed_gate_in_room, unpressed_button_in_room, guard_alive_in_room, hp_ratio, has_big_life_potion, has_small_red_potion, has_exit_door_open
Cross-Room Multi-Hop 6 dst_is_known_dead_end, dst_leads_to_unvisited_frontier, dst_leads_to_landmark, edge_fail_or_death_rate, in_n_room_cycle, dst_entry_hazard

Crucial anti-memorization property: Level numbers, room IDs, and step timestamps are never fed to the network. The model physically cannot index “Level 2 Room 14” — it only reasons over relational dungeon structure.

Forward-Pass Equations (21,665 Params, 198.4 KB JSON)

Given candidate matrix X_t ∈ R^{K_t × 30} and recurrent memory h_{t-1} ∈ R^{32} (zeroed at episode start):

  1. Shared Candidate Encoder (30 → 128 → 64):

    \[e_i = \text{ReLU}\!\big(W_2\,\text{ReLU}(W_1 x_{t,i} + b_1) + b_2\big) \in \mathbb{R}^{64}\]
  2. Room-Choice Summary:

    \[m_t = \frac{1}{K_t}\sum_{i=1}^{K_t} e_i \in \mathbb{R}^{64}\]
  3. Gated Cross-Room Working Memory (32-dim GRU-style update):

    \[z_t = \sigma(W_z [m_t, h_{t-1}] + b_z), \quad \tilde{h}_t = \tanh(W_g [m_t, h_{t-1}] + b_g)\] \[h_t = (1 - z_t) \odot h_{t-1} + z_t \odot \tilde{h}_t \in \mathbb{R}^{32}\]
  4. Nonlinear Actor Head (96 → 32 → 1):

    \[\ell_i = w_\pi^\top \tanh\!\big(W_\pi [e_i, h_t] + b_\pi\big) + b_{\text{out}}, \quad \pi_\theta(a_i \mid s_t, h_t) = \frac{\exp(\ell_i / \tau)}{\sum_j \exp(\ell_j / \tau)}\]

    (Why nonlinear? A linear head w_e^T e_i + w_h^T h_t adds the exact same constant w_h^T h_t to every candidate i, which cancels out identically inside softmax! The tanh hidden layer lets h_t gate and modulate candidate preferences.)

  5. Critic Head (96 → 1, training only):

    \[V_\theta(s_t, h_t) = w_v^\top [m_t, h_t] + b_v\]

We implemented analytical Backpropagation Through Time (BPTT) in pure NumPy and verified all 13 parameter tensors against central finite differences (eps = 1e-6, max gradient error < 1e-5), plus verified < 1e-4 numerical parity between NumPy training and pure-Python stdlib inference.


4. Zero-LLM Training Methodology: Semi-MDP PPO-Clip + Go-Explore

We trained ActorCriticPolicy with zero LLMs using headless/train_ppo_headless.py:

  • Automatic Game-State Rewards (r_t, strictly from /state):
    • +1.5 discovering an unvisited room (gated to 0.0 once an open exit door is known with the sword so Prince sprints to the exit instead of farming side rooms)
    • +2.5 pressing an unpressed switch, picking up the sword, or drinking a red/big potion
    • +3.0 defeating a guard
    • +25.0 clearing the level, plus a clear-conditioned speed bonus +15.0 × max(0, 1 - steps / max_steps) (rewarding speed only on actual clears so RL never discovers “die fast to avoid step penalties”)
    • -0.08 per decision step, -1.0 re-entering a is_known_dead_end room, -1.5 room-cycle revisit or failed/stalled goal, -5.0 death
  • Semi-MDP GAE (γ = 0.98, λ = 0.95): Because some rooms have only K = 1 legal goal (forced transition or blind sprint), rewards accumulated during intermediate K = 1 steps are folded cleanly into the preceding K ≥ 2 decision before computing Generalized Advantage Estimation.
  • PPO-Clip Objective (ε = 0.2, AdamW, global grad clip 0.5):

    \[\mathcal{L}(\theta) = -\mathbb{E}\!\left[\min\!\big(r_t(\theta)\hat{A}_t,\;\text{clip}(r_t(\theta), 1-\epsilon, 1+\epsilon)\hat{A}_t\big)\right] + c_v \mathbb{E}\!\left[(V_\theta - \hat{R}_t)^2\right] + \beta\,\mathbb{E}\!\left[D_{\text{KL}}(\pi_\theta \,\|\, \pi_{\text{ref}})\right] - c_e \mathbb{E}[H(\pi_\theta)]\]
  • Go-Explore Frontier Archive (Training Only): During training on uncleared levels, we archive in-memory snapshots of newly reached (level, room, row, have_sword, pressed_count) cells and start 30% of training rollouts from frontier cells. All evaluations run 100% from level start with zero snapshots and an empty fog map.
  • Adaptive Inference Temperature (--adaptive_temp=True): At runtime, Prince acts greedily (τ = 0.0) on normal rooms, but automatically bumps sampling temperature to τ = 0.85 if a room/edge repeats (rm_t >= 3 or cycle detected) so a deterministic policy never locks up forever on an unfamiliar puzzle.

5. Empirical Results: Headless SDLPoP vs. Physical Raspberry Pi 1

Strict Zero-Cheat Blank-Slate Evaluation in Headless SDLPoP (0 LLMs, 0 Snapshots, 0 Quicksaves)

Checkpoint 1: models/pop_ppo_l123.json (Trained on Levels 1–3)

Level Clear Rate Avg Steps Avg Deaths Avg Wall Time Avg Rooms
Level 1 3/3 (100%) 114.0 0.0 0.344 s 14.0
Level 2 3/3 (100%) 97.0 1.0 0.337 s 19.7
Level 3 3/3 (100%) 158.7 2.3 0.673 s 16.0

Checkpoint 2: models/pop_ppo_l1234.json (Expanded to Levels 1–4, Including Level 4’s Magic Mirror 'M' & Close-Gate 'b' Plates)

Level Clear Rate Avg Steps Avg Deaths Avg Wall Time Avg Rooms
Level 1 3/3 (100%) 115.0 0.0 0.52 s 14.0
Level 2 3/3 (100%) 133.7 1.3 6.27 s 20.3
Level 3 3/3 (100%) 114.3 0.0 0.70 s 15.0
Level 4 2/3 (66.7%) 186.0 0.0 0.94 s 18.0
Total 11/12 (91.7%) — — — —

Live Physical Raspberry Pi 1 Deployment (models/pop_ppo_l123.json, 0 LLMs, 0 Quicksaves)

Deploying the headless-trained 198 KB weights directly onto the live Raspberry Pi 1 surfaced real-world uinput timing deltas (needing > 1 tick LEFTSHIFT pre-sleep so careful-step chords don’t land in the same frame and trigger a run, plus longer UP + dir holds on 2-tile standing jumps). Once ported generically into pi_bridge.py, the exact same 198 KB model cleared Levels 1, 2, and 3 live on physical hardware:

Level (Live Pi 1) Cleared Motor Steps Deaths Guards Rooms Local Calls API Calls p50 / p95 Wall Time
Level 1 Yes 184 2 1 16 25 0 16.1 / 53.9 ms 11.3 min
Level 2 Yes 203 8 14 21 25 0 13.2 / 40.9 ms 17.7 min
Level 3 Yes 191 3 4 16 27 0 14.4 / 101.1 ms 16.1 min

6. Honest Generalization Test: Frozen L1–3 Model on Unseen Levels 4–7

How do we know this isn’t memorizing a path? Besides structurally withholding level/room IDs from the network, we ran the frozen models/pop_ppo_l123.json weights (trained only on Levels 1–3) zero-shot on completely unseen Levels 4, 5, 6, and 7:

Unseen Level Clear Rate Avg Rooms Avg Guards Avg Deaths Primary Bottleneck
Level 4 0/3 3.0 0.0 0.0 Motor stall (climb_ledge / safe_hang_drop) + unseen 'b' trap plates
Level 5 0/3 7.7 0.3 0.3 Generalized 8 unseen rooms deep, beat a guard, reached Shadow thief + chompers (rm=24) before climb_ledge stall
Level 6 0/3 3.0 0.0 249 Fell into spikes in rm=2 (fast retry loop)
Level 7 0/3 1.0 0.0 0.0 Spawned above a gap, spammed climb_ledge -> no_climbable_ledge

The honest ML takeaway: Training on Levels 1–4 synthesizes a general dungeon-solving policy over known mechanics (proven by navigating 8 rooms deep into unseen Level 5). However, no frozen RL policy can zero-shot invent brand-new out-of-distribution mechanics it has never encountered — like Level 6’s mandatory jump into an apparent abyss, Level 8’s mouse-triggered switch, or Level 12’s sword-sheathing Shadow merge. Those require curiosity-driven online exploration or rare deliberative reasoning.


7. The Two-Timescale GEN #N Self-Improving 12 fps Live Broadcast

Finally, we turned the headless C engine into a 24/7 autonomous 1280×720 @ 12 fps live broadcast (headless/local_live_stream.py) by adding an opt-in software framebuffer readout (pop_set_render_enabled(1) + pop_get_framebuffer()) that renders crisp 3× pixel-art frames alongside a live HUD sidebar (Vitals, real-time PPO+GRU candidate probability bars synced on both multi-choice and forced single-goal turns, and a growing 2D Fog-of-War minimap) for zero-OBS ffmpeg streaming to YouTube Live / Twitch:

Live 1280x720 12 fps Zero-LLM PPO+GRU Broadcast HUD and Fog-of-War Minimap Live 1280×720 @ 12 fps broadcast view: 3× Headless SDLPoP framebuffer alongside real-time PPO+GRU candidate probabilities, latency/API counters (API CALLS: 0), and the growing 2D Fog-of-War minimap.

  1. Fast Autonomous Inner Loop (24/7, 0 LLMs, $0): Every 4 episodes, the stream runs an online PPO-Clip + GAE + Clear-Conditioned Speed Bonus update with a KL anchor (kl_beta = 0.05) back to the base checkpoint (which we added after observing textbook catastrophic forgetting during a 26-generation unanchored overnight run — even as that run pushed Level 2 to 23/23 clears and 66 best steps!), increments GEN #N live on screen, and appends structured diagnostics (death_rooms, failed_skills_top3, best_steps_by_level) to data/stream_rl_history.jsonl.
  2. Slow Daily Outer Loop (Once-a-Day Scheduled Audit): Once every 24 hours, a scheduled Antigravity automation reads data/stream_rl_history.jsonl, pinpoints the #1 recurring motor or mechanic failure, implements a generic fix + unit test, verifies no regressions, and reloads the stream.

Next up: replacing the hand-coded motor skills (climb_ledge, fight_guard, chomper crossing) with a learned 12 Hz neural motor controller trained directly on our 24,506× Headless SDLPoP engine, and expanding the curriculum across Levels 5–12.