Fix the remote player interpolation in a co-op game

Review the AI's codeEasy12 min

Your task

In your co-op game, remote players snapped to each new server position as it arrived, about 15 times a second, so they rubber-banded at 60 frames a second. The fix keeps a buffer of timestamped snapshots, draws remote players slightly in the past, and blends between the two snapshots around that time.

An assistant wrote interpolate_remote_position(snapshot_times, snapshot_xs, now, interp_delay). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • snapshot_times, snapshot_xs: the buffered snapshots, read in pairs: snapshot i says the player was at snapshot_xs[i] at time snapshot_times[i]. Times are in ascending order.
  • now: the current time. interp_delay: how far in the past to draw.
  • Return the position to draw.

Rules the tests check:

  • If the two lists differ in length, use only as many snapshots as the shorter one has. With no snapshots, return 0.
  • The render time is now - interp_delay.
  • At or before the first snapshot's time, return the first position.
  • At or after the last snapshot's time, return the last position. Never guess beyond the newest snapshot.
  • Otherwise find the first snapshot i + 1 whose time is at or after the render time, and blend linearly between snapshots i and i + 1. If those two have the same time, return the position of i + 1.
  • Answers within 0.000001 of the expected value pass.

Examples

interpolate_remote_position(snapshot_times: list[float], snapshot_xs: list[float], now: float, interp_delay: float) -> float
Example 1
Inputinterpolate_remote_position([0, 1, 2], [0, 10, 30], 2, 1)
Output10
Example 2
Inputinterpolate_remote_position([0, 1, 2], [0, 10, 30], 2, 0.5)
Output20
Example 3
Inputinterpolate_remote_position([0, 1, 2], [0, 10, 30], 0.2, 1)
Output0