Side-Scrolling Bird Autopilot Across Variable Pipe Layouts
Medium · Software Engineering Fundamentals · Data Scientist · Online Assessment
Problem Statement
Implement a step-by-step flight controller for a side-scrolling obstacle game. An airborne square avatar travels rightward at constant horizontal speed while downward acceleration pulls it toward the floor, and triggering a flap resets its vertical speed to a fixed upward launch value. Vertical barrier pairs extend down from the ceiling and up from the floor, leaving an open rectangular window between them. Contacting the floor, the ceiling, or the solid part of any barrier ends the flight immediately.
Your function should_flap(state) is queried once before every simulation step and must return True to flap or False to glide:
from dataclasses import dataclass
from typing import List
GRAVITY = 1.0 # vertical speed lost on each non-flap step
FLAP_VELOCITY = 5.0 # vertical speed assigned on a flap step
DX = 3.0 # rightward advance on every step
R = 2.0 # half-width and half-height of the avatar's square hitbox
SCREEN_HEIGHT = 100.0 # y-coordinate of the lethal upper boundary
@dataclass
class Pipe:
x_left: float # left x-boundary of the barrier pair
x_right: float # right x-boundary of the barrier pair
gap_bottom: float # upper edge of the lower barrier
gap_top: float # lower edge of the upper barrier
@dataclass
class GameState:
x: float # current horizontal center of the avatar
y: float # current vertical center (0 is ground, upward is positive)
vy: float # current vertical velocity per step
pipes: List[Pipe] # currently visible barriers, ordered by ascending x_left
def should_flap(state: GameState) -> bool:
"""Return True to flap on the upcoming step, or False to glide."""
Each simulation step applies the following deterministic rules in order:
- Velocity update: If
should_flap(state)returnsTrue,vybecomesFLAP_VELOCITY(5.0); if it returnsFalse,vybecomesvy - GRAVITY(vy - 1.0). - Position update:
ybecomesy + vy, andxbecomesx + DX(x + 3.0). - Collision check: Represent the avatar by its axis-aligned square
[x - R, x + R] x [y - R, y + R](4.0 x 4.0). A crash occurs after the move if:y - R <= 0.0(touches or crosses the ground),y + R >= SCREEN_HEIGHT(touches or crosses the ceiling), or- for any barrier in the course with horizontal overlap (
x + R >= pipe.x_leftandx - R <= pipe.x_right), the vertical square is not strictly inside the opening (y - R <= pipe.gap_bottomory + R >= pipe.gap_top).
Because this comes from an open-ended engineering prompt, starter.py fixes the concrete assumptions above: physics constants are shared across runs and known to your code, state.pipes exposes the barriers currently within forward view sorted by x_left, and the ceiling is lethal just like the ground. A single controller must clear arbitrary unseen barrier layouts whose gap elevations, opening heights, and spacings change both within a course and across courses. When a state is already physically inescapable, should_flap must still return a bool and delay the crash for as many steps as possible.
Examples
Example 1
Input:
state = GameState(
x=6.0,
y=24.0,
vy=-1.0,
pipes=[Pipe(x_left=19.0, x_right=34.0, gap_bottom=38.0, gap_top=70.0)],
)
Output:
True
Explanation: Advancing at DX = 3.0 with half-size R = 2.0, the avatar's right edge (x + 2.0) first reaches x_left = 19.0 on step 4 (x = 18.0, spanning [16.0, 20.0]), where its center needs y > 38.0 + 2.0 = 40.0. Gliding on step 1 drops to y = 22.0 (vy = -2.0); even flapping on steps 2, 3, and 4 climbs only to 27.0 -> 32.0 -> 37.0 <= 40.0, crashing into the lower barrier. Flapping immediately climbs 29.0 -> 34.0 -> 39.0 -> 44.0 > 40.0 and clears the opening safely.
Example 2
Input:
state = GameState(
x=0.0,
y=52.0,
vy=1.0,
pipes=[Pipe(x_left=24.0, x_right=36.0, gap_bottom=30.0, gap_top=62.0)],
)
Output:
False
Explanation: Gliding on the current step moves to (x = 3.0, y = 52.0, vy = 0.0), well aligned with the upcoming safe vertical corridor (32.0, 60.0) and leaving ample room to stay safe across the upcoming barriers without climbing toward the upper rim prematurely.
Example 3
Input:
Start at (x=0.0, y=50.0, vy=0.0) across the full course:
pipes = [
Pipe(x_left=36.0, x_right=48.0, gap_bottom=62.0, gap_top=90.0),
Pipe(x_left=84.0, x_right=96.0, gap_bottom=10.0, gap_top=38.0),
Pipe(x_left=132.0, x_right=144.0, gap_bottom=54.0, gap_top=82.0),
]
Output:
Survives all 50 steps until the hitbox clears x_right = 144.0
Explanation: The controller climbs into the high first opening (64.0, 88.0), crests early so gravity is already pulling it downward as it exits x = 48.0, drops cleanly into the low second opening (12.0, 36.0) just 36.0 units later, and climbs back into the third opening (56.0, 80.0).
Constraints
GRAVITY = 1.0,FLAP_VELOCITY = 5.0,DX = 3.0,R = 2.0,SCREEN_HEIGHT = 100.0.state.pipesis sorted in non-decreasing order ofx_left, withpipe.x_left < pipe.x_rightand0.0 < pipe.gap_bottom < pipe.gap_top < SCREEN_HEIGHT.- Touching any boundary (
y - R <= 0.0,y + R >= SCREEN_HEIGHT,y - R <= gap_bottom, ory + R >= gap_topwhilex + R >= x_leftandx - R <= x_right) counts as a crash. should_flapmust always return abool(TrueorFalse), use only the Python standard library, and run within a few milliseconds per step without hardcoded per-map schedules.
Step-by-step walkthrough
Clarify the open rules and state assumptions
Because several simulation details can vary across open-ended engineering prompts, start by stating clear, explicit assumptions that match
starter.py:- Step physics: On a flap,
vyis set toFLAP_VELOCITY = 5.0; otherwisevydecreases byGRAVITY = 1.0. Next, height updates (y += vy) and horizontal position advances (x += DX = 3.0). - Bounding-box collision: The avatar is a
4 x 4square ([x - R, x + R] x [y - R, y + R]withR = 2.0). Boundary contact ends the flight: the run crashes ify - R <= 0.0(ground),y + R >= SCREEN_HEIGHT(100.0, ceiling), or the square overlaps a pipe horizontally (x + R >= pipe.x_leftandx - R <= pipe.x_right) whiley - R <= pipe.gap_bottomory + R >= pipe.gap_top. - Visibility & doomed states:
should_flapinspectsstate.pipes(sorted byx_left). Clearing every barrier is the primary goal, and when a state is already inescapable, surviving more steps is strictly preferred over crashing early.
Before coding, examine the trajectory of one single flap followed by gliding (
vy = +5, +4, +3, +2, +1, 0, -1, -2, ...):steps after flap: 1 2 3 4 5 6 7 8 9 10 11 vy on that step: +5 +4 +3 +2 +1 0 -1 -2 -3 -4 -5 height gain dy: +5 +9 +12 +14 +15 +15 +14 +12 +9 +5 0A single flap lifts the avatar by
+15units over5steps (15horizontal units) and returns to its starting height after11steps (33horizontal units). Every maneuver through barrier openings is built by chaining arcs like this.- Step physics: On a flap,
Build the single-step simulator and collision check
Because the physics are deterministic and known to our code, we first write an exact model of one vertical step (
step) and one collision test (crashed).Notice two clean details in
crashed: 1. We pass an extramarginparameter that expands the half-size toR + margin. Withmargin = 0.0, it enforces the exact crash boundary; withmargin = 1.0, it asks for1unit of extra buffer from pipes, ground, and ceiling whenever space permits. 2. Becausepipesis sorted byx_left, as soon aspipe.x_left > x + half, every later pipe lies strictly ahead of the hitbox, allowing an immediatebreak.from typing import Dict, List, Tuple from dataclasses import dataclass GRAVITY = 1.0 FLAP_VELOCITY = 5.0 DX = 3.0 R = 2.0 SCREEN_HEIGHT = 100.0 @dataclass class Pipe: x_left: float x_right: float gap_bottom: float gap_top: float @dataclass class GameState: x: float y: float vy: float pipes: List[Pipe] def step(y: float, vy: float, flap: bool) -> Tuple[float, float]: """Advance vertical state by one step: update velocity first, then height.""" if flap: next_vy = FLAP_VELOCITY else: next_vy = vy - GRAVITY next_y = y + next_vy return next_y, next_vy def crashed(x: float, y: float, pipes: List[Pipe], margin: float) -> bool: """Return True if a box of half-size (R + margin) at (x, y) hits ground, ceiling, or pipe.""" half = R + margin if y - half <= 0.0 or y + half >= SCREEN_HEIGHT: return True for pipe in pipes: if pipe.x_left > x + half: break if pipe.x_right >= x - half: if y - half <= pipe.gap_bottom or y + half >= pipe.gap_top: return True return FalseWhy reactive rules and 1-step checks crash
A reactive threshold rule — such as "flap whenever
ysits below the midpoint of the next opening" — ignores vertical momentum and upcoming transitions. In Example 3, after clearing a high opening (62..90), a midpoint tracker keeps hovering neary = 76until exitingx = 48, leaving too little horizontal room for gravity to drop into the low opening (10..38) starting atx = 84.Checking only
1step ahead fails too. Walk through Example 1:x = 6.0, y = 24.0, vy = -1.0facingPipe(x_left=19.0, x_right=34.0, gap_bottom=38.0, gap_top=70.0). On step4(x = 18.0), the avatar's right edge (18.0 + 2.0 = 20.0) overlapsx_left = 19.0, so its center needsy > 38.0 + 2.0 = 40.0:step: 1 2 3 4 (overlaps x_left = 19 at x = 18) flap, flap, flap, flap: 29 -> 34 -> 39 -> 44 (44 > 40: SAFE!) glide, flap, flap, flap: 22 -> 27 -> 32 -> 37 (37 <= 40: CRASH!)Gliding on step
1(y = 22.0) looks completely harmless for one step, yet it makes crashing into the lower barrier three steps later unavoidable. Good decisions now require simulating multiple steps ahead.Key idea: memoized lookahead search
Suppose we look
HORIZON = 30steps ahead and ask: "starting from(x, y, vy)withdepthsteps left, what is the maximum number of steps the avatar can survive?"Branching over
glideandflapat every step without caching explores2^30(~1.07 billion) trajectories. However, within a singleshould_flapcall, the horizontal coordinatexat remaining depthdepthis alwaysstate.x + (HORIZON - depth) * DX, no matter which flaps occurred earlier.Thus
(depth, round(y, 6), round(vy, 6))uniquely identifies a subproblem: -depth:1 .. 29(< 30values). -vyaftertsteps: eithervy_0 - t * g(never flapped) or5 - k * g(ksteps since the last flap), at mostt + 1 <= 31values. - Integerystrictly inside(2, 98): at most95heights.Instead of
1.07 billionaction sequences, at most30 * 31 * 95 = 88,350distinct states exist — and because webreakas soon asbest == depth(a trajectory survived the entire remaining horizon), typical calls visit fewer than200states.HORIZON = 30 # steps of lookahead (90 horizontal units) SAFETY_MARGIN = 1.0 # extra box clearance preferred whenever a wide path exists def steps_survived( x: float, y: float, vy: float, depth: int, pipes: List[Pipe], margin: float, memo: Dict[Tuple[int, float, float], int], ) -> int: """Return the maximum number of steps (out of `depth`) survivable from (x, y, vy).""" if depth == 0: return 0 # Within a single should_flap call, x is uniquely determined by `depth` # (x = state.x + (HORIZON - depth) * DX), so (depth, y, vy) identifies the state. key = (depth, round(y, 6), round(vy, 6)) if key in memo: return memo[key] best = 0 for flap in (False, True): next_y, next_vy = step(y, vy, flap) next_x = x + DX if crashed(next_x, next_y, pipes, margin): continue survived = 1 + steps_survived( next_x, next_y, next_vy, depth - 1, pipes, margin, memo ) if survived > best: best = survived if best == depth: break memo[key] = best return bestScore actions with a two-pass safety margin
Now
should_flapcombines three clean engineering choices:- Test gliding first and short-circuit: Evaluate
glide_steps = score_action(state, False, margin, memo). Whenglide_steps == HORIZON(as in Example 2 aty = 52.0, vy = 1.0), gliding is already safe for30steps — returnFalseimmediately without running theflapsearch. - Prefer
SAFETY_MARGIN = 1.0, fall back to0.0: Search first withmargin = 1.0(6 x 6buffered box) so trajectories stay comfortably clear of barrier corners on normal courses. Only when neither choice survivesHORIZONwithmargin = 1.0(such as threading a razor-thin gap), re-run withmargin = 0.0(4 x 4exact hitbox). - Graceful degradation when doomed: If neither choice survives
HORIZONeven withmargin = 0.0, returnflap_steps > glide_stepsto postpone impact as long as physically possible.
We never carry
memoacross separate calls toshould_flap: re-planning fresh on every step (receding-horizon control) naturally incorporates newly visible barriers and corrects small disturbances.def score_action( state: GameState, flap: bool, margin: float, memo: Dict[Tuple[int, float, float], int], ) -> int: """Return steps survived (out of HORIZON) if the bird takes `flap` now and plays optimally.""" next_y, next_vy = step(state.y, state.vy, flap) next_x = state.x + DX if crashed(next_x, next_y, state.pipes, margin): return 0 return 1 + steps_survived( next_x, next_y, next_vy, HORIZON - 1, state.pipes, margin, memo ) def should_flap(state: GameState) -> bool: """Called once per step. Return True to flap on this step, or False to glide.""" for margin in (SAFETY_MARGIN, 0.0): memo: Dict[Tuple[int, float, float], int] = {} glide_steps = score_action(state, False, margin, memo) if glide_steps == HORIZON: return False flap_steps = score_action(state, True, margin, memo) if flap_steps == HORIZON: return True return flap_steps > glide_steps- Test gliding first and short-circuit: Evaluate
Choose the horizon length from flight geometry
How large must
HORIZONbe? It needs to span a full-screen vertical climb or drop plus crossing a barrier pair: - Climbing ~90vertical units at+5units per step takes18steps. - Crossing a20..30-wide barrier pair (plus the4-wide hitbox) atDX = 3takes8..11steps.Their sum is
18 + 11 = 29steps, soHORIZON = 30(90horizontal units) covers both a full-corridor climb/descent and the barrier passage while running in well under0.5 msper step on average.Trace three hard scenarios
Let us trace how
should_flaphandles three demanding situations:- Example 3 transition — high opening (
62..90atx = 36..48), then low opening (10..38atx = 84..96): Between clearing the first barrier (x = 48, step16, needingy > 64) and reaching the second barrier (x = 84, step28, needingy < 36), only12steps elapse for a29+unit drop. BecauseHORIZON = 30(90horizontal units) already sees the low barrier atx = 84before the avatar enters the high barrier, any branch that flaps late inside[36, 48]crashes inside the lookahead search. The controller therefore crests early inside the first opening and exitsx = 48already descending. - Razor-thin gap (
42..48atx = 16..17, height6for a4-tall hitbox): UnderSAFETY_MARGIN = 1.0(half = 3.0),y - 3 > 42(y > 45) andy + 3 < 48(y < 45) is empty. Pass 1 (margin = 1.0) finds no30-step trajectory, and Pass 2 (margin = 0.0,half = 2.0) seamlessly threadsy = 45through(44, 46)near the flat crest of a flap arc (dy = +14, +15, +15, +14). - Doomed state (
x = 0, y = 6, vy = -4facing an unreachable opening65..92atx = 15..45): Gliding hitsy = 6 - 5 = 1 <= 2immediately (glide_steps = 0), whereas flapping climbs11 -> 15 -> 18 -> 20across steps1..4before colliding with the barrier atx = 15on step5(flap_steps = 4).flap_steps > glide_steps(4 > 0) returnsTrue, maximizing survival.
- Example 3 transition — high opening (
Complete solution
from typing import Dict, List, Tuple from dataclasses import dataclass # Physics shared by every map (known to the code, per the statement). GRAVITY = 1.0 # vy drops by this much on a step without a flap FLAP_VELOCITY = 5.0 # a flap sets vy to this value DX = 3.0 # horizontal move per step R = 2.0 # half-size of the bird's box SCREEN_HEIGHT = 100.0 # assumed lethal, like the ground HORIZON = 30 # steps of lookahead (90 horizontal units) SAFETY_MARGIN = 1.0 # extra box clearance preferred whenever a wide path exists @dataclass class Pipe: x_left: float # left edge of the pipe pair x_right: float # right edge of the pipe pair gap_bottom: float # top of the lower pipe gap_top: float # bottom of the upper pipe @dataclass class GameState: x: float # bird's horizontal position (its center) y: float # bird's height above the ground (its center); y grows upward vy: float # vertical velocity per step; positive means rising pipes: List[Pipe] # the pipes the autopilot can see, sorted by x_left def step(y: float, vy: float, flap: bool) -> Tuple[float, float]: """Advance vertical state by one step: update velocity first, then height.""" if flap: next_vy = FLAP_VELOCITY else: next_vy = vy - GRAVITY next_y = y + next_vy return next_y, next_vy def crashed(x: float, y: float, pipes: List[Pipe], margin: float) -> bool: """Return True if a box of half-size (R + margin) at (x, y) hits ground, ceiling, or pipe.""" half = R + margin # Touching the ground (y <= half) or screen top (y >= SCREEN_HEIGHT - half) ends the run. if y - half <= 0.0 or y + half >= SCREEN_HEIGHT: return True for pipe in pipes: # pipes is sorted by x_left: once a pipe starts strictly past our right edge, none after can overlap. if pipe.x_left > x + half: break if pipe.x_right >= x - half: # Horizontally overlapping: safe only when strictly inside (gap_bottom, gap_top). if y - half <= pipe.gap_bottom or y + half >= pipe.gap_top: return True return False def steps_survived( x: float, y: float, vy: float, depth: int, pipes: List[Pipe], margin: float, memo: Dict[Tuple[int, float, float], int], ) -> int: """Return the maximum number of steps (out of `depth`) survivable from (x, y, vy).""" if depth == 0: return 0 # Within a single should_flap call, x is uniquely determined by `depth` # (x = state.x + (HORIZON - depth) * DX), so (depth, y, vy) identifies the state. key = (depth, round(y, 6), round(vy, 6)) if key in memo: return memo[key] best = 0 # Try gliding (False) before flapping (True) to stop immediately on a calm safe path. for flap in (False, True): next_y, next_vy = step(y, vy, flap) next_x = x + DX if crashed(next_x, next_y, pipes, margin): continue survived = 1 + steps_survived( next_x, next_y, next_vy, depth - 1, pipes, margin, memo ) if survived > best: best = survived if best == depth: # Cannot beat surviving all remaining `depth` steps; skip remaining branch. break memo[key] = best return best def score_action( state: GameState, flap: bool, margin: float, memo: Dict[Tuple[int, float, float], int], ) -> int: """Return steps survived (out of HORIZON) if the bird takes `flap` now and plays optimally.""" next_y, next_vy = step(state.y, state.vy, flap) next_x = state.x + DX if crashed(next_x, next_y, state.pipes, margin): return 0 return 1 + steps_survived( next_x, next_y, next_vy, HORIZON - 1, state.pipes, margin, memo ) def should_flap(state: GameState) -> bool: """Called once per step. Return True to flap on this step, or False to glide.""" # Phase 1: Try with extra clearance (SAFETY_MARGIN = 1.0) first, then exact rules (0.0) # when threading a razor-thin gap where extra clearance cannot fit. for margin in (SAFETY_MARGIN, 0.0): # memo: maps (remaining_depth, rounded_y, rounded_vy) -> max steps survived memo: Dict[Tuple[int, float, float], int] = {} # Check gliding first: if gliding survives the whole horizon, skip computing flap! glide_steps = score_action(state, False, margin, memo) if glide_steps == HORIZON: return False flap_steps = score_action(state, True, margin, memo) if flap_steps == HORIZON: return True # Phase 2: Doomed state (no sequence survives HORIZON even with margin = 0.0). # Delay the unavoidable crash as long as possible using the margin = 0.0 scores. return flap_steps > glide_steps✅ Submit now — all tests should pass.
Intuition & how it works
Imagine tossing a ball forward through a sequence of suspended rings set at very different altitudes: each tap launches the ball upward at a fixed vertical speed (vy = +5), cresting +15 units higher after 5 steps before gravity pulls it back down. Because the step equations are deterministic and known, there is no need to tune a fragile height threshold. Instead, before each step, we simulate both options (glide vs. flap) across a lookahead horizon (a fixed window of future steps simulated ahead of the present) and pick an action that preserves a collision-free trajectory through upcoming openings.
Simple reactive rules fail because vertical motion has momentum and asymmetry. Chasing the midpoint of the nearest gap hovers too high inside an elevated opening and cannot accelerate downward fast enough when a low opening immediately follows. Checking only a single step ahead fails too, because gliding into open air can be harmless right now while leaving too few steps to climb up to an approaching ledge; conversely, branching blindly across 30 steps without caching evaluates 2^30 (~1.07 billion) action sequences per step.
We make that search fast and reliable using memoization (caching the maximum survivable steps for each (remaining_depth, y, vy) state so identical trajectories reached via different flap histories are solved once) plus a two-pass safety margin (an extra clearance buffer around the hitbox used whenever affordable, automatically falling back to 0.0 in tight squeezes). Trace Example 1 from x = 6.0, y = 24.0, vy = -1.0 approaching Pipe(x_left=19.0, x_right=34.0, gap_bottom=38.0, gap_top=70.0) (4 steps away at x = 18.0, where the 4 x 4 axis-aligned bounding box, a non-rotated square [x - 2, x + 2] x [y - 2, y + 2], needs center y > 40.0):
- Test
glide(False) first: Gliding drops to(x = 9.0, y = 22.0, vy = -2.0). Even if the controller flaps on steps2, 3, 4(+5.0per step), center height reaches27.0 -> 32.0 -> 37.0 <= 40.0, hitting the lower barrier on step4(glide_steps = 3 < HORIZON). - Test
flap(True) next: Flapping moves to(x = 9.0, y = 29.0, vy = +5.0). Flapping across steps2, 3, 4climbs34.0 -> 39.0 -> 44.0 > 40.0, entering the opening cleanly and surviving all30steps (flap_steps == HORIZON). - Act and re-plan:
should_flapreturnsTruenow and runs a fresh search on the next step (receding-horizon control, executing only the immediate decision and re-planning from the updated state every step).
Complexity
- Time per call:
O(S * P). HereSis the count of distinct(depth, rounded_y, rounded_vy)states visited during the search, andPis the number of nearby pipes checked bycrashedbefore stopping atpipe.x_left > x + half. With integer constants andHORIZON = 30,depthtakes< 30values,vytakes at most31values, and integeryinside(2, 98)takes95values, boundingSby~88,350states instead of2^30 ≈ 1.07 billionraw branches — and because the search exits immediately when a branch survivesHORIZON(and skipsflapwheneverglidealready survivesHORIZON), typical calls visit fewer than200states. - Space:
O(S + HORIZON). Thememodictionary stores at mostSentries for the active search and the call stack is at mostHORIZONframes deep; nothing is kept between consecutive calls.
Edge cases
- Empty course (
pipes = []): Only the ground (y <= 2) and ceiling (y >= 98) apply; the avatar glides smoothly toward the floor and flaps just abovey = 2indefinitely. - Razor-thin openings (
gap_top - gap_bottombarely exceeding2 * R): A6-tall opening (42..48) leaves zero strict interior underSAFETY_MARGIN = 1.0(2 * (2 + 1) = 6), so Pass 1 (margin = 1.0) finds no30-step path and Pass 2 (margin = 0.0) takes over to thready = 45across the flat peak of a flap arc. - Avatar already horizontally overlapping a barrier:
crashedevaluates every step identically, keepingyconstrained to(gap_bottom + half, gap_top - half)untilx - half > pipe.x_right. - Inescapable states: When no trajectory reaches
HORIZONeven atmargin = 0.0,flap_steps > glide_stepsselects whichever choice delays impact strictly longer, always returning abool. - Non-integer parameters: Rounding
yandvyto6decimal places in thememokey merges equivalent floating-point states cleanly.
Common mistakes
- Evaluating
flapeven whenglidealready survivesHORIZON: Running both searches unconditionally roughly doubles per-step work; returningFalseimmediately whenglide_steps == HORIZONskips the second branch on most steps. - Sharing
memoacross separateshould_flapcalls: Within one call,depthmaps tostate.x + (HORIZON - depth) * DX; on the next step,state.xhas advanced by+3.0, shifting every pipe collision relative todepth. - Treating the avatar as a point instead of a
2R x 2Rsquare: Checkinggap_bottom < y < gap_topignores half-sizeRboth vertically (y - R,y + R) and horizontally (x - R,x + R). - Using too short a horizon (
HORIZON <= 10): A short window cannot spot a steep high-to-low drop before the avatar is already too high to fall in time. - Debugging on physically unsolvable hand-crafted courses: Always validate custom test layouts with an exact reachable-set oracle before blaming the planner.
Alternative approaches
- Forward breadth-first reachable sets: Propagate the set of survivable
(y, vy)pairs forward from step1toHORIZON, recording which step-1 action (FalseorTrue) can reach each state. Same polynomial state bound with zero recursion, though slower on easy steps because it expands all reachable states instead of stopping on the first safe trajectory. - Full-course backward dynamic programming: When all pipes are visible from the start, sweep backward from the final barrier to
x = 0once to mark viable(step, y, vy)states, turning onlineshould_flapqueries intoO(1)lookups. - Heuristic A* search: Prioritize states by farthest
xreached plus vertical clearance from the next opening center when horizons stretch to hundreds of steps.
Follow-up questions
- Suppose the simulator's true physics deviate slightly from your assumed step equations (for instance, rounding heights or updating position before velocity). How resilient is your controller, and how could it detect that discrepancy at runtime? Re-planning from the observed
GameStateon every step cancels small cumulative drift, andSAFETY_MARGIN = 1.0keeps nominal trajectories1unit clear of walls so minor rounding differences rarely cause collisions. However, a structural mismatch such as updatingy += vybefore changingvydelays every flap's lift by one step! To detect mismatches online, cache your predicted(next_y, next_vy)on steptand compare it against(state.y, state.vy)on stept + 1to compute the residual (the difference between predicted and observed state); non-zero residuals immediately flag a physics discrepancy so the controller can switch update order or widenSAFETY_MARGIN. - If gravity and flap impulse were unknown and each observation exposed only
(x, y)coordinates withoutvy, how would you infer the motion parameters online? Estimate velocities by differencing consecutive positions (dx = x_t - x_{t-1}andvy_t = y_t - y_{t-1}). Across two consecutive non-flap steps, vertical speed drops byg, givingg = vy_{t-1} - vy_t(for instance, heights50 -> 49 -> 47yieldvy = -1, -2, revealingg = 1); if coordinates are noisy or quantized, average over glide steps via least squares (choosing parameter estimates that minimize squared prediction errors). Executing one exploratory flap in open sky revealsFLAP_VELOCITY = y_t - y_{t-1}, and flapping from two distinct vertical velocities distinguishes whether a flap resetsvyor adds an impulse tovy. - How should your decision function behave when a pipe layout has no survivable trajectory? Production control code must stay deterministic, fast, and exception-free (
return bool) even when a crash is unavoidable. When neitherglidenorflapreachesHORIZONeven undermargin = 0.0, comparingflap_steps > glide_stepsmaximizes distance traveled rather than raising an error, freezing, or oscillating randomly. In offline benchmark suites, filter procedural maps through an exact brute-force reachability check so physically impossible layouts are separated from controller failures. - Under what conditions would a policy trained via reinforcement or imitation learning outperform online lookahead search, and why is search preferable here? When dynamics are deterministic, low-dimensional, and known, online lookahead search generalizes zero-shot to arbitrary unseen pipe geometries, whereas a reinforcement learning policy can misgeneralize on gap patterns underrepresented during training. Learned policies shine when dynamics are stochastic or unknown, inputs are raw high-dimensional pixels, or strict microsecond latency budgets forbid multi-step rollouts. Even in that regime, imitation learning (training a compact neural network to imitate decisions produced offline by a lookahead search oracle) converges far faster and more reliably than model-free trial-and-error reinforcement learning.
Follow-up questions
- Suppose the simulator's true physics deviate slightly from your assumed step equations (for instance, rounding heights or updating position before velocity). How resilient is your controller, and how could it detect that discrepancy at runtime?
- If gravity and flap impulse were unknown and each observation exposed only `(x, y)` coordinates without `vy`, how would you infer the motion parameters online?
- How should your decision function behave when a pipe layout has no survivable trajectory?
- Under what conditions would a policy trained via reinforcement or imitation learning outperform online lookahead search, and why is search preferable here?
Similar questions
- Lookahead Autopilot for Canyon Gates
- Submarine Ballast Controller for Variable Reef Channels
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging