KatInterview

Flappy Bird Auto-Pilot with Lookahead Planning

Dynamic ProgrammingModel answer
MediumModel answerDynamic Programminggame-physicssimulationtrajectory-planning

Last 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 gravity units per time step
  • A jump action adds jump_strength units 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 position
  • v (float): current vertical velocity
  • gravity (float): downward acceleration per tick
  • obstacles (list): each element is (x, bottom_y, top_y) where:
    • x is horizontal distance to the obstacle
    • bottom_y and top_y define the vertical gap you must pass through

Physics model (per tick):

  1. Position updates: y_new = y + v
  2. Velocity updates: v_new = v - gravity (no jump) or v_new = v + jump_strength (jump)

Additional parameters (use defaults if not provided):

  • jump_strength=5.0
  • ceiling_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