TExcelTAD
Home › Multiplayer Game Networking › Game Networking Exercises

Game Networking Exercises

Netcode bugs hide in small pure functions: a comparison that breaks when a counter wraps, an off-by-one in an ack mask, an interpolation that runs past the newest snapshot. Each exercise below is one of those functions, with tests already written. Complete the code marked TODO until the output matches the expected output, then compare with the solution.

Tip: Run the starter first. It prints wrong answers, which shows what the tests expect. Change the code, press Ctrl+Enter, repeat.

Exercise 1: Sequence numbers that wrap

Topics: Reliability over UDP

Write isNewer(a, b) for 16-bit sequence numbers: true when a is ahead of b by less than half of the 65536 range, counting around the wrap.

ts · try it yourself
function isNewer(a: number, b: number): boolean {
  // TODO: handle the wrap from 65535 to 0
  return a > b;
}

console.log(isNewer(10, 5), isNewer(5, 10));       // true false
console.log(isNewer(2, 65534), isNewer(65534, 2)); // true false
console.log(isNewer(30000, 0), isNewer(40000, 0)); // true false
true false
false true
true true

Expected output:

text
true false
true false
true false
Show solution
ts
function isNewer(a: number, b: number): boolean {
  return (a > b && a - b <= 32768) || (a < b && b - a > 32768);
}

Exercise 2: Quantize a position

Topics: Quantization & Delta Compression

Complete bitsFor, encode and decode for a value in [min, max] with a given precision. encode must clamp values outside the range.

ts · try it yourself
function bitsFor(min: number, max: number, precision: number): number {
  return 0; // TODO: smallest number of bits for (max - min) / precision + 1 steps
}
function encode(v: number, min: number, max: number, precision: number): number {
  return 0; // TODO: clamp, then round((v - min) / precision)
}
function decode(q: number, min: number, precision: number): number {
  return 0; // TODO
}

console.log(bitsFor(0, 100, 0.01), bitsFor(-512, 512, 0.01), bitsFor(0, 1, 1 / 255));
for (const v of [12.345, -3, 250]) {
  const q = encode(v, 0, 100, 0.01);
  console.log(v, '->', q, '->', decode(q, 0, 0.01).toFixed(2));
}
0 0 0
12.345 -> 0 -> 0.00
-3 -> 0 -> 0.00
250 -> 0 -> 0.00

Expected output:

text
14 17 8
12.345 -> 1235 -> 12.35
-3 -> 0 -> 0.00
250 -> 10000 -> 100.00
Show solution
ts
function bitsFor(min: number, max: number, precision: number): number {
  return Math.ceil(Math.log2(Math.round((max - min) / precision) + 1));
}
function encode(v: number, min: number, max: number, precision: number): number {
  const c = Math.max(min, Math.min(max, v));
  return Math.round((c - min) / precision);
}
function decode(q: number, min: number, precision: number): number {
  return min + q * precision;
}

Math.round inside bitsFor protects against floating-point results such as 254.99999999999997 for 1 / (1/255).

Exercise 3: Build the ack header

Topics: Reliability over UDP

Given the set of sequence numbers received so far (no wrap-around in this exercise), return the header the receiver should send: ack = the newest received, and bits where bit i means ack - 1 - i was received (only the 32 packets before ack).

ts · try it yourself
function ackHeader(received: number[]): { ack: number; bits: string } {
  let ack = 0, bits = 0;
  // TODO
  return { ack, bits: bits.toString(2).padStart(8, '0') };
}

console.log(ackHeader([0, 1, 2, 3]));
console.log(ackHeader([5, 7, 8, 10]));
console.log(ackHeader([100, 60, 99, 67]));
{ ack: 0, bits: '00000000' }
{ ack: 0, bits: '00000000' }
{ ack: 0, bits: '00000000' }

Expected output:

text
{ ack: 3, bits: '00000111' }
{ ack: 10, bits: '00010110' }
{ ack: 100, bits: '00000001' }
Show solution
ts
function ackHeader(received: number[]): { ack: number; bits: string } {
  const ack = Math.max(...received);
  let bits = 0;
  for (const s of received) {
    const d = ack - s;                           // 1 = the packet just before ack
    if (d >= 1 && d <= 32) bits = (bits | (1 << (d - 1))) >>> 0;
  }
  return { ack, bits: bits.toString(2).padStart(8, '0') };
}

60 is 40 packets older than 100, so it no longer fits in the mask; 67 is 33 older, also outside the 32-bit window.

Exercise 4: Interpolate between snapshots

Topics: Snapshot Interpolation

sample(buffer, t) returns the position at render time t from snapshots sorted by time. Blend linearly between the two snapshots around t; before the first snapshot return the first; after the last, hold the last (no extrapolation).

ts · try it yourself
type Snap = { t: number; x: number };
function sample(buf: Snap[], t: number): number {
  return buf[buf.length - 1].x; // TODO
}

const buf: Snap[] = [{ t: 100, x: 0 }, { t: 150, x: 10 }, { t: 200, x: 30 }, { t: 300, x: 30 }];
for (const t of [50, 100, 125, 175, 250, 400]) console.log(t, sample(buf, t));
50 30
100 30
125 30
175 30
250 30
400 30

Expected output:

text
50 0
100 0
125 5
175 20
250 30
400 30
Show solution
ts
function sample(buf: Snap[], t: number): number {
  if (t <= buf[0].t) return buf[0].x;
  for (let i = 1; i < buf.length; i++) {
    const a = buf[i - 1], b = buf[i];
    if (t <= b.t) return a.x + (b.x - a.x) * (t - a.t) / (b.t - a.t);
  }
  return buf[buf.length - 1].x;
}

Exercise 5: Reconcile

Topics: Server Reconciliation

A snapshot says the player is at serverX after input ack. Return the corrected predicted position and the inputs that are still pending. Movement: x += move * 3 per input.

ts · try it yourself
type Input = { seq: number; move: number };
function reconcile(serverX: number, ack: number, pending: Input[]): { x: number; pending: number[] } {
  // TODO: drop acknowledged inputs, then replay the rest from serverX
  return { x: serverX, pending: pending.map((i) => i.seq) };
}

const pending: Input[] = [{ seq: 7, move: 1 }, { seq: 8, move: 1 }, { seq: 9, move: 0 }, { seq: 10, move: -1 }];
console.log(reconcile(21, 7, pending));
console.log(reconcile(20, 8, pending));    // the server disagrees by 1 unit
console.log(reconcile(30, 10, pending));   // everything acknowledged
{ x: 21, pending: [ 7, 8, 9, 10 ] }
{ x: 20, pending: [ 7, 8, 9, 10 ] }
{ x: 30, pending: [ 7, 8, 9, 10 ] }

Expected output:

text
{ x: 21, pending: [ 8, 9, 10 ] }
{ x: 17, pending: [ 9, 10 ] }
{ x: 30, pending: [] }
Show solution
ts
function reconcile(serverX: number, ack: number, pending: Input[]): { x: number; pending: number[] } {
  const rest = pending.filter((i) => i.seq > ack);
  let x = serverX;
  for (const i of rest) x += i.move * 3;
  return { x, pending: rest.map((i) => i.seq) };
}

Exercise 6: A token bucket

Topics: Rate Limiting & Abuse

Allow on average rate messages per second with bursts up to capacity. allow(nowMs) refills by elapsed time, then spends one token if there is one.

ts · try it yourself
class TokenBucket {
  private tokens: number;
  private last = 0;
  constructor(private rate: number, private capacity: number) { this.tokens = capacity; }
  allow(nowMs: number): boolean {
    // TODO: refill (rate tokens per second, never above capacity), then try to spend 1
    return true;
  }
}

const chat = new TokenBucket(1, 3);               // 1 message/s, bursts of 3
const times = [0, 100, 200, 300, 400, 1500, 1600, 4000, 4100, 4200, 4300];
console.log(times.map((t) => (chat.allow(t) ? 'ok' : 'drop')).join(' '));
ok ok ok ok ok ok ok ok ok ok ok

Expected output:

text
ok ok ok drop drop ok drop ok ok ok drop
Show solution
ts
allow(nowMs: number): boolean {
  this.tokens = Math.min(this.capacity, this.tokens + ((nowMs - this.last) / 1000) * this.rate);
  this.last = nowMs;
  if (this.tokens < 1) return false;
  this.tokens -= 1;
  return true;
}

Exercise 7: Rewind with a limit

Topics: Lag Compensation

The server stores the target's x per tick (50 ms ticks). A shot at aimX claims the shooter saw tick viewTick and arrives at nowTick. Rewind only if the rewind is at most maxMs; otherwise test against the present. A hit is |aimX - x| <= 5.

ts · try it yourself
const xs = [0, 8, 16, 24, 32, 40, 48, 56, 64, 72];   // target x at ticks 0..9
function judge(aimX: number, viewTick: number, nowTick: number, maxMs: number): string {
  return 'MISS'; // TODO
}

console.log(judge(24, 3, 6, 200));   // 150 ms rewind: allowed
console.log(judge(24, 3, 9, 200));   // 300 ms rewind: too far
console.log(judge(72, 3, 9, 200));   // aimed where the target is now
console.log(judge(19, 2, 4, 200));   // near the edge of the hitbox
MISS
MISS
MISS
MISS

Expected output:

text
HIT at x=24
MISS at x=72 (rewind 300 ms refused)
HIT at x=72 (rewind 300 ms refused)
HIT at x=16
Show solution
ts
function judge(aimX: number, viewTick: number, nowTick: number, maxMs: number): string {
  const rewindMs = (nowTick - viewTick) * 50;
  const ok = rewindMs <= maxMs;
  const x = ok ? xs[viewTick] : xs[nowTick];
  const hit = Math.abs(aimX - x) <= 5;
  return `${hit ? 'HIT' : 'MISS'} at x=${x}${ok ? '' : ` (rewind ${rewindMs} ms refused)`}`;
}

Bonus: break the simulator

Open the complete simulator in Server Reconciliation and change the code:

  1. Make the client's move() 10% faster than the server's (a "speed hack"). Watch the corrections appear, and think about how a server would detect it (Never Trust the Client).
  2. Send only the last input per packet instead of the last three, and set the loss to 10%. How large do the corrections get?
  3. Change INTERP_DELAY to 30 ms and the jitter to 50 ms. What happens to the bot?

Test yourself

In Exercise 3, why is packet 67 not included in the ack bits when ack = 100?

  1. It was lost
  2. It is 33 packets older than ack, outside the 32-bit window
  3. Bits only track even numbers
  4. Only the newest packet is acked

In Exercise 5, the server acks input 8 at x = 20, and inputs 9 (move 0) and 10 (move −1) are pending. Where does the player end up?

  1. 20
  2. 17
  3. 23
  4. 21