Flappy Bird Auto-Pilot with Lookahead Planning
Dynamic ProgrammingModel answerLast updated
Design a physics-based agent that decides when to jump by projecting future trajectories and checking collision-free paths through upcoming obstacles.
Problem
You're building an autopilot for a side-scrolling game with vertical navigation. The player character moves through a 2D space where:
- Gravity continuously pulls downward by
gravityunits per time step - A jump action adds
jump_strengthunits to vertical velocity - Obstacles with vertical gaps approach horizontally at constant speed
Your task is to implement should_jump(y, v, gravity, obstacles) -> bool that decides whether to trigger a jump at this moment.
Parameters:
y(float): current vertical positionv(float): current vertical velocitygravity(float): downward acceleration per tickobstacles(list): each element is(x, bottom_y, top_y)where:xis horizontal distance to the obstaclebottom_yandtop_ydefine the vertical gap you must pass through
Physics model (per tick):
- Position updates:
y_new = y + v - Velocity updates:
v_new = v - gravity(no jump) orv_new = v + jump_strength(jump)
Additional parameters (use defaults if not provided):
jump_strength=5.0ceiling_height=float('inf')(upper boundary)speed=1.0(horizontal obstacle approach rate)
Constraints:
- The character must remain in
[0, ceiling_height]at all times - When an obstacle reaches horizontal position 0, the character's vertical position must be within
[bottom_y, top_y]
Example:
should_jump(y=10, v=0, gravity=1, obstacles=[(5, 8, 12)])
# Returns False — waiting is better than jumping immediately
What decision maximizes survival probability through all known obstacles?
Hints
Hint 1
Don't just check the nearest obstacle — a greedy approach may create an unrecoverable state for obstacles further ahead
Hint 2
Determine when each obstacle will arrive, then explore whether any sequence of future actions can navigate all of them
Hint 3
Use memoization to avoid recalculating feasibility from the same (time, position, velocity) state
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Problem Analysis
The naive strategy — "jump whenever I'm about to hit the bottom edge of the next gap" — fails because:
- It ignores obstacles beyond the immediate next one
- Jumping too early may cause you to overshoot and hit the ceiling or an upper pipe edge
- It doesn't account for velocity accumulation
The robust solution uses lookahead trajectory planning: simulate all possible action sequences forward in time and pick actions that keep at least one viable path open.
Algorithm Design
Core idea: At each decision point, ask "if I don't jump now, can I still survive through all upcoming obstacles?" If yes, conserve the jump for later (maintains flexibility). If no, jump only if jumping creates a survivable path.
Implementation steps:
-
Preprocess obstacles into gates
Convert each obstacle's(x, bottom_y, top_y)into an arrival timet = ceil(x / speed)and constraint interval. If multiple obstacles arrive at the same tick, intersect their allowed ranges. -
Define the planning horizon
Extend a few ticks beyond the farthest obstacle to ensure the character doesn't thread a gap into an unrecoverable trajectory. -
Recursive feasibility search with memoization
feasible(tick, position, velocity): if tick > horizon: return True next_pos = position + velocity if next_pos violates [0, ceiling] or gate constraint: return False return feasible(tick+1, next_pos, velocity - gravity) OR feasible(tick+1, next_pos, velocity + jump_strength) -
Make the decision
- Compute
y_next = y + v(the position at tick 1 regardless of action) - Check if "no jump" leads to a feasible future:
feasible(1, y_next, v - gravity) - If yes, return
False(don't jump) - Otherwise check if jumping helps:
feasible(1, y_next, v + jump_strength) - If yes, return
True - If neither works, fall back to a heuristic (e.g., jump if below the target gap's midpoint)
- Compute
Why This Works
- Correctness: The search exhaustively explores both actions at every future tick, pruning only provably unsafe branches. If the current state is survivable, we choose an action that leads to another survivable state.
- Optimality for survival: By preferring "no jump" when feasible, we maintain maximum future flexibility — velocity stays lower, giving more reaction time.
- Replanning: Running this decision every tick adapts to changing game state.
Complexity Analysis
Let H be the horizon (farthest gate tick + padding), C the ceiling height:
- Time: With memoization on
(tick, position, velocity), the state space is bounded byO(H² × C)for discrete positions. Each state does O(1) work. Real-valued positions may explore O(2^H) states in the worst case, but bounds pruning keeps it tractable. - Space: O(state count) for memoization + O(H) recursion depth.
Edge Cases
- Already inside a gap: The search finds "no jump" feasible and returns False.
- Obstacle at x=0 or negative: Ignored — your action can't affect the current tick.
- High velocity at peak: Naturally handled; the simulation projects future positions accurately.
- Multiple gates at the same tick: Intersect their intervals; an empty intersection makes that state infeasible.
- No obstacles: Only floor/ceiling constraints apply over a short horizon.
Code
import math
from functools import lru_cache
def should_jump(y, v, gravity, obstacles,
jump_strength=5.0, ceiling_height=float('inf'),
speed=1.0, pad=3):
"""
Decide whether to jump based on lookahead trajectory planning.
Returns True if jumping is necessary to survive upcoming obstacles.
"""
# Build gate map: tick -> (min_y, max_y)
gates = {}
for x, lo, hi in obstacles:
tick = math.ceil(x / speed - 1e-9)
if tick <= 0:
continue
existing = gates.get(tick, (-math.inf, math.inf))
gates[tick] = (max(existing[0], lo), min(existing[1], hi))
horizon = (max(gates.keys()) if gates else 0) + pad
def is_safe(tick, pos):
"""Check if position satisfies bounds and gate constraints."""
if pos < 0 or pos > ceiling_height:
return False
if tick in gates:
lo, hi = gates[tick]
if pos < lo or pos > hi:
return False
return True
@lru_cache(maxsize=None)
def feasible(tick, pos, vel):
"""Check if any action sequence from this state survives to horizon."""
if tick >= horizon:
return True
next_pos = round(pos + vel, 9)
if not is_safe(tick + 1, next_pos):
return False
# Try both: coast (no jump) and jump
coast_vel = round(vel - gravity, 9)
jump_vel = round(vel + jump_strength, 9)
return (feasible(tick + 1, next_pos, coast_vel) or
feasible(tick + 1, next_pos, jump_vel))
# Position at tick 1 (determined by current velocity, not action)
y_next = round(y + v, 9)
if not is_safe(1, y_next):
# Already doomed; heuristic fallback
nearest_gate = min((t, gates[t]) for t in gates if t > 0) if gates else None
if nearest_gate:
mid = (nearest_gate[1][0] + nearest_gate[1][1]) / 2
return y < mid
return False
# Prefer not jumping if it keeps a path open
if feasible(1, y_next, round(v - gravity, 9)):
return False
# Otherwise jump if it helps
if feasible(1, y_next, round(v + jump_strength, 9)):
return True
# Both fail; heuristic
if gates:
t_near, (lo, hi) = min((t, gates[t]) for t in gates if t > 0)
return y < (lo + hi) / 2
return v < 0 # Falling toward floor
Common Mistakes
- Greedy local decisions — checking only the immediate next obstacle misses compound effects
- Off-by-one errors — forgetting that position updates before velocity, so a jump affects tick+2, not tick+1
- Ignoring ceiling — overshooting upward is as fatal as hitting the floor
- Not extending the horizon — stopping exactly at the last gate may approve a trajectory that crashes immediately after
This solution avoids all of these by explicitly simulating the full physics model through a sufficient horizon and exploring all action sequences.