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:

  1. Velocity update: If should_flap(state) returns True, vy becomes FLAP_VELOCITY (5.0); if it returns False, vy becomes vy - GRAVITY (vy - 1.0).
  2. Position update: y becomes y + vy, and x becomes x + DX (x + 3.0).
  3. 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_left and x - R <= pipe.x_right), the vertical square is not strictly inside the opening (y - R <= pipe.gap_bottom or y + 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.pipes is sorted in non-decreasing order of x_left, with pipe.x_left < pipe.x_right and 0.0 < pipe.gap_bottom < pipe.gap_top < SCREEN_HEIGHT.
  • Touching any boundary (y - R <= 0.0, y + R >= SCREEN_HEIGHT, y - R <= gap_bottom, or y + R >= gap_top while x + R >= x_left and x - R <= x_right) counts as a crash.
  • should_flap must always return a bool (True or False), use only the Python standard library, and run within a few milliseconds per step without hardcoded per-map schedules.

Step-by-step walkthrough

  1. 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, vy is set to FLAP_VELOCITY = 5.0; otherwise vy decreases by GRAVITY = 1.0. Next, height updates (y += vy) and horizontal position advances (x += DX = 3.0).
    • Bounding-box collision: The avatar is a 4 x 4 square ([x - R, x + R] x [y - R, y + R] with R = 2.0). Boundary contact ends the flight: the run crashes if y - R <= 0.0 (ground), y + R >= SCREEN_HEIGHT (100.0, ceiling), or the square overlaps a pipe horizontally (x + R >= pipe.x_left and x - R <= pipe.x_right) while y - R <= pipe.gap_bottom or y + R >= pipe.gap_top.
    • Visibility & doomed states: should_flap inspects state.pipes (sorted by x_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    0
    

    A single flap lifts the avatar by +15 units over 5 steps (15 horizontal units) and returns to its starting height after 11 steps (33 horizontal units). Every maneuver through barrier openings is built by chaining arcs like this.

  2. 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 extra margin parameter that expands the half-size to R + margin. With margin = 0.0, it enforces the exact crash boundary; with margin = 1.0, it asks for 1 unit of extra buffer from pipes, ground, and ceiling whenever space permits. 2. Because pipes is sorted by x_left, as soon as pipe.x_left > x + half, every later pipe lies strictly ahead of the hitbox, allowing an immediate break.

    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 False
    
  3. Why reactive rules and 1-step checks crash

    A reactive threshold rule — such as "flap whenever y sits 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 near y = 76 until exiting x = 48, leaving too little horizontal room for gravity to drop into the low opening (10..38) starting at x = 84.

    Checking only 1 step ahead fails too. Walk through Example 1: x = 6.0, y = 24.0, vy = -1.0 facing Pipe(x_left=19.0, x_right=34.0, gap_bottom=38.0, gap_top=70.0). On step 4 (x = 18.0), the avatar's right edge (18.0 + 2.0 = 20.0) overlaps x_left = 19.0, so its center needs y > 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.

  4. Key idea: memoized lookahead search

    Suppose we look HORIZON = 30 steps ahead and ask: "starting from (x, y, vy) with depth steps left, what is the maximum number of steps the avatar can survive?"

    Branching over glide and flap at every step without caching explores 2^30 (~1.07 billion) trajectories. However, within a single should_flap call, the horizontal coordinate x at remaining depth depth is always state.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 (< 30 values). - vy after t steps: either vy_0 - t * g (never flapped) or 5 - k * g (k steps since the last flap), at most t + 1 <= 31 values. - Integer y strictly inside (2, 98): at most 95 heights.

    Instead of 1.07 billion action sequences, at most 30 * 31 * 95 = 88,350 distinct states exist — and because we break as soon as best == depth (a trajectory survived the entire remaining horizon), typical calls visit fewer than 200 states.

    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 best
    
  5. Score actions with a two-pass safety margin

    Now should_flap combines three clean engineering choices:

    1. Test gliding first and short-circuit: Evaluate glide_steps = score_action(state, False, margin, memo). When glide_steps == HORIZON (as in Example 2 at y = 52.0, vy = 1.0), gliding is already safe for 30 steps — return False immediately without running the flap search.
    2. Prefer SAFETY_MARGIN = 1.0, fall back to 0.0: Search first with margin = 1.0 (6 x 6 buffered box) so trajectories stay comfortably clear of barrier corners on normal courses. Only when neither choice survives HORIZON with margin = 1.0 (such as threading a razor-thin gap), re-run with margin = 0.0 (4 x 4 exact hitbox).
    3. Graceful degradation when doomed: If neither choice survives HORIZON even with margin = 0.0, return flap_steps > glide_steps to postpone impact as long as physically possible.

    We never carry memo across separate calls to should_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
    
  6. Choose the horizon length from flight geometry

    How large must HORIZON be? It needs to span a full-screen vertical climb or drop plus crossing a barrier pair: - Climbing ~90 vertical units at +5 units per step takes 18 steps. - Crossing a 20..30-wide barrier pair (plus the 4-wide hitbox) at DX = 3 takes 8..11 steps.

    Their sum is 18 + 11 = 29 steps, so HORIZON = 30 (90 horizontal units) covers both a full-corridor climb/descent and the barrier passage while running in well under 0.5 ms per step on average.

  7. Trace three hard scenarios

    Let us trace how should_flap handles three demanding situations:

    • Example 3 transition — high opening (62..90 at x = 36..48), then low opening (10..38 at x = 84..96): Between clearing the first barrier (x = 48, step 16, needing y > 64) and reaching the second barrier (x = 84, step 28, needing y < 36), only 12 steps elapse for a 29+ unit drop. Because HORIZON = 30 (90 horizontal units) already sees the low barrier at x = 84 before 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 exits x = 48 already descending.
    • Razor-thin gap (42..48 at x = 16..17, height 6 for a 4-tall hitbox): Under SAFETY_MARGIN = 1.0 (half = 3.0), y - 3 > 42 (y > 45) and y + 3 < 48 (y < 45) is empty. Pass 1 (margin = 1.0) finds no 30-step trajectory, and Pass 2 (margin = 0.0, half = 2.0) seamlessly threads y = 45 through (44, 46) near the flat crest of a flap arc (dy = +14, +15, +15, +14).
    • Doomed state (x = 0, y = 6, vy = -4 facing an unreachable opening 65..92 at x = 15..45): Gliding hits y = 6 - 5 = 1 <= 2 immediately (glide_steps = 0), whereas flapping climbs 11 -> 15 -> 18 -> 20 across steps 1..4 before colliding with the barrier at x = 15 on step 5 (flap_steps = 4). flap_steps > glide_steps (4 > 0) returns True, maximizing survival.
  8. 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):

  1. Test glide (False) first: Gliding drops to (x = 9.0, y = 22.0, vy = -2.0). Even if the controller flaps on steps 2, 3, 4 (+5.0 per step), center height reaches 27.0 -> 32.0 -> 37.0 <= 40.0, hitting the lower barrier on step 4 (glide_steps = 3 < HORIZON).
  2. Test flap (True) next: Flapping moves to (x = 9.0, y = 29.0, vy = +5.0). Flapping across steps 2, 3, 4 climbs 34.0 -> 39.0 -> 44.0 > 40.0, entering the opening cleanly and surviving all 30 steps (flap_steps == HORIZON).
  3. Act and re-plan: should_flap returns True now 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). Here S is the count of distinct (depth, rounded_y, rounded_vy) states visited during the search, and P is the number of nearby pipes checked by crashed before stopping at pipe.x_left > x + half. With integer constants and HORIZON = 30, depth takes < 30 values, vy takes at most 31 values, and integer y inside (2, 98) takes 95 values, bounding S by ~88,350 states instead of 2^30 ≈ 1.07 billion raw branches — and because the search exits immediately when a branch survives HORIZON (and skips flap whenever glide already survives HORIZON), typical calls visit fewer than 200 states.
  • Space: O(S + HORIZON). The memo dictionary stores at most S entries for the active search and the call stack is at most HORIZON frames 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 above y = 2 indefinitely.
  • Razor-thin openings (gap_top - gap_bottom barely exceeding 2 * R): A 6-tall opening (42..48) leaves zero strict interior under SAFETY_MARGIN = 1.0 (2 * (2 + 1) = 6), so Pass 1 (margin = 1.0) finds no 30-step path and Pass 2 (margin = 0.0) takes over to thread y = 45 across the flat peak of a flap arc.
  • Avatar already horizontally overlapping a barrier: crashed evaluates every step identically, keeping y constrained to (gap_bottom + half, gap_top - half) until x - half > pipe.x_right.
  • Inescapable states: When no trajectory reaches HORIZON even at margin = 0.0, flap_steps > glide_steps selects whichever choice delays impact strictly longer, always returning a bool.
  • Non-integer parameters: Rounding y and vy to 6 decimal places in the memo key merges equivalent floating-point states cleanly.

Common mistakes

  • Evaluating flap even when glide already survives HORIZON: Running both searches unconditionally roughly doubles per-step work; returning False immediately when glide_steps == HORIZON skips the second branch on most steps.
  • Sharing memo across separate should_flap calls: Within one call, depth maps to state.x + (HORIZON - depth) * DX; on the next step, state.x has advanced by +3.0, shifting every pipe collision relative to depth.
  • Treating the avatar as a point instead of a 2R x 2R square: Checking gap_bottom < y < gap_top ignores half-size R both 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 step 1 to HORIZON, recording which step-1 action (False or True) 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 = 0 once to mark viable (step, y, vy) states, turning online should_flap queries into O(1) lookups.
  • Heuristic A* search: Prioritize states by farthest x reached 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 GameState on every step cancels small cumulative drift, and SAFETY_MARGIN = 1.0 keeps nominal trajectories 1 unit clear of walls so minor rounding differences rarely cause collisions. However, a structural mismatch such as updating y += vy before changing vy delays every flap's lift by one step! To detect mismatches online, cache your predicted (next_y, next_vy) on step t and compare it against (state.y, state.vy) on step t + 1 to 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 widen SAFETY_MARGIN.
  • 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? Estimate velocities by differencing consecutive positions (dx = x_t - x_{t-1} and vy_t = y_t - y_{t-1}). Across two consecutive non-flap steps, vertical speed drops by g, giving g = vy_{t-1} - vy_t (for instance, heights 50 -> 49 -> 47 yield vy = -1, -2, revealing g = 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 reveals FLAP_VELOCITY = y_t - y_{t-1}, and flapping from two distinct vertical velocities distinguishes whether a flap resets vy or adds an impulse to vy.
  • 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 neither glide nor flap reaches HORIZON even under margin = 0.0, comparing flap_steps > glide_steps maximizes 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

Similar questions

More Aqr interview questions

All 3 Aqr questions →