How NetWars Works Chapter 17 of 21, plus appendices

17. Complete simulation algorithms

This chapter is the simulation written out as algorithms: one game frame in exact order, then every object the frame touches (your ship, aliens, missiles, pods, shots, satellites, the other players' copies), each with its state machine, its integer arithmetic and the order of its checks. Chapters 4 to 8 explain the same behaviour gently; here nothing is left to guess. If you write the pseudocode below in your language, with the same integer rules, you get the same game, frame for frame.

Read it like a reference: section 1 is the frame and the cross-cutting rules (randomness, counters, "this frame or last frame"), section 2 the helpers everything else uses, sections 3 to 9 the objects and the level, section 10 the multiplayer side. Every section ends with an Exact rules box. Tags: O read in the reconstructed code (which is byte-identical to the original) or seen in a recorded run, D derived from the code but not watched, H hypothesis.

0. Conventions used in the pseudocode

NotationMeaning
int16, int32signed integers that wrap around like the original's 16- and 32-bit registers. Every plain variable below is int16 unless said otherwise.
a >> narithmetic shift right (rounds toward minus infinity: -1 >> 7 = -1). In JavaScript: >> on a value that fits in 32 bits, not Math.trunc(a / 2**n).
a << n on an int16wraps to 16 bits (for example 0xC0 << 8 = 0xC000 = −16384).
position, velocity (lvec)three signed 64-bit integers ("raw"). One world unit = 65,536 raw (chapter 3). mid32(x) = x >> 16 cut to 32 bits; mid16(x) = x >> 16 cut to 16 bits (the "middle word"). Writing mid(x) = v means x = v · 216 with all other bits 0 (only satelliteSpawn does this, on a cleared vector). The exponent law of 2.2 assumes every axis difference is below 231 units, because mid32 drops the bits above 47.
a / binteger division, truncated toward zero (the original's IDIV); every division in this chapter has non-negative operands.
-w < r < wpseudocode for "-w < r and r < w", not a chained comparison (in JavaScript write both tests).
x & m == vnever used without brackets: bit tests are always written (x & m) == v.
switch … k:a case ends where the next case label starts: there is no fall-through unless a comment says "falls through" (only the Fighter, 4.4). break leaves the switch and goes on with the code after it; continue goes to the next pass of the enclosing loop.
recordsfield names of bodies (type, pos, home, distExp, dir, camX/Y/Z, fwd, right, up, pitchRate, rollRate, yawRate, model, state, speed, maxTurn, maxSpeed, accel, particles, hp, visible, target) and shots (state, pos, vel, fwd, right, up) are those of chapter 14; scale(model) is the model's first word (chapter 16).
axes, directionsthree int16 in Q14 (16384 = 1.0, chapter 3).
angles, ratessteps of 1/2048 turn per frame.
speed of a bodyraw units: a body moves fwd · speed raw per frame, which is speed / 4 world units (Q14 axis × speed = speed · 214 raw = speed / 4 units).
frameone pass of the flight loop: 18.2 per second in single player, about 70 per second in multiplayer (our emulator runs, chapter 2).
sound(n), message(text, frames)side effects that do not change the simulation: PC-speaker effect n (chapter 10); the centre message messagePtr = text; messageTimer = frames.

1. The frame, exactly

1.1 Single player

The flight loop of main (src/main.c). Each line is one call or one assignment, in the original order O.

loop forever:                                   // one iteration = one frame
  if key latch ESC:                             // set by the key handler, chapter 11
      score[me] = 0                             // an abandoned game scores nothing
      leave loop                                // -> 9.4 "after the loop"
  if aliensLeft == 0 and shields > 0:
      leave loop                                // level cleared -> 9.4
  tick = 0                                      // timer ticks (18.2 Hz) counted from here
  show the page drawn in the previous frame     // waits for the vertical retrace
  if key latch F2:                              // pause
      clear F2; busy-wait until F2 latched again; clear F2
  frameCount   += 1
  if bumpImmunity > 0: bumpImmunity -= 1
  if tumble > 0:       tumble -= 1
  clear the hidden page with flashColor; flashColor = 0; empty the draw list
  playerUpdate()                                // 3
  if not spectator: playerShotsUpdate()         // 7.2   (spectator is always 0 here)
  if (frameCount & 63) == 0: alienSpawn()         // 4.2
  aliensUpdate()                                // 4.1
  enemyMissilesUpdate()                         // 5.2
  playerMissilesUpdate()                        // 5.4
  podsUpdate()                                  // 6
  alienShotsUpdate()                            // 7.5
  if (frameCount & 127) == 0 and not spectator: satelliteSpawn()   // 8.1
  satelliteUpdate()                             // 8.2
  draw stars, flush the draw list, draw the score text
  if shields > 0:
      draw radar and instruments
      if messageTimer > 0: draw message; messageTimer -= 1
  else if playerDeadScreen() == 1:              // 9.3
      leave loop
  busy-wait while tick < 1                      // at most 18.2 frames per second

1.2 Multiplayer (the local step)

Same loop, other branches O. There are no aliens, missiles or pods; the other players exist only as copies filled from their packets (section 10).

loop forever:
  if key latch ESC:
      if not spectator: score[me] = 0
      leave loop                                // player: name screen, new life; spectator: lobby
  postPeerListens()                             // 10.1: re-arm one receive per live peer
  if not spectator: sendStateIfIdle()           // 10.1: broadcast the state as it is NOW,
                                                //       i.e. as the previous frame left it
  tick = 0
  show the previous page
  if key latch F2: clear F2; clear F2           // no pause in multiplayer
  frameCount += 1; count down bumpImmunity and tumble as above
  clear the page with flashColor; flashColor = 0; empty the draw list
  playerUpdate()                                // 3 (Enter toggles the cloak here)
  if not spectator: playerShotsUpdate()         // 7.2, multiplayer branch
  remotePlayersUpdate()                         // 10.2
  remoteShotsUpdate()                           // 10.3
  if (frameCount & 127) == 0 and not spectator: satelliteSpawn()
  satelliteUpdate()                             // 8.2 incl. the peers' satellites
  draw stars, list; if not spectator: draw score
  if shields > 0: radar, instruments, message as above
  else: playerDeadScreen()                      // never returns 1 in multiplayer
  netSyncFrame()                                // 10.4: wait for peers, apply their hits

1.3 Which values each step sees

The order decides who sees whose old position. "Previous frame" means the value as the previous frame left it O.

StepReadsAs of
playerUpdatekeys, mouse; haveTarget and the aliens' visible == 2 marks (missile launch)input: now; marks: previous frame's aliensUpdate
playerShotsUpdatealiens, enemy missiles, pods, own satellite; the peers' ships and satellitesaliens, missiles, pods: end of the previous frame (they move later). The ship and the shots: this frame. Peers: their last packet
alienSpawnship position and axesthis frame (after playerUpdate)
alien behaviour (AI)its own display exponent distExpits previous frame's move (a new alien: 0)
alien steeringship position; the pod it is aftership: this frame; pod: previous frame (pods move after aliens), but pod states changed earlier this frame by your shots are seen
alien ram testship position, axes, bumpImmunitythis frame; immunity may have been set by an earlier alien slot in this same frame
enemyMissilesUpdateship positionthis frame; missiles launched this frame move at once
playerMissilesUpdateits target alienthis frame (aliens already moved); deaths from this frame are seen
podsUpdatethe captor (towing alien)this frame
alienShotsUpdateship positionthis frame; shots fired this frame move and are tested at once
satelliteUpdateship position, bumpImmunity; peers' item events this frame; peers' events: their last packet
netSyncFramepeers' hit reports and status wordstheir last packet (see 10.4 about repeats)

1.4 Randomness

The game uses the Borland C library generator and nothing else O (a full search of the sources finds exactly the five call sites below).

srand(t):  seed32 = t                 // called once at program start with time(0) cut to 16 bits
rand():    seed32 = seed32 * 0x015A4E35 + 1      (mod 2^32)
           return (seed32 >> 16) & 0x7FFF        // 0 .. 32767
WhereWhenCalls, in orderFormula
playerBump (9.1)each bump: in aliensUpdate (single player) or remotePlayersUpdate (multiplayer)2: pitch, then rollrate = (rand() * 2 / 32768) * 0x60 − 0x30 (32-bit arithmetic) = −48 or +48
satelliteSpawn (8.1)a frame with (frameCount & 127) == 0 and no own satellite3: x, then y, then zmid = rand() * 20000 / 32768 − 10000 (32-bit, then a 64-bit subtraction) = −10000 … 9999

Within one frame the order is therefore: bumps (in alien-slot order) before the satellite. A single-player game replays identically given the same inputs D: the seed (time(0) cut to 16 bits at program start, and every rand() call made since, including earlier games of the session), the input sampled in every frame, and, for each level, the number of level-introduction frames (they set the camera's starting roll, 9.4).

1.5 Counters and periodic events

CounterResetChangedUsed for
frameCount0 at every level start (single player) and every life (multiplayer, after the name screen)+1 near the start of each frame, before any object moves, so the first simulated frame has 1alien spawn when (frameCount & 63) == 0 (frames 64, 128, …); satellite when (… & 127) == 0 (128, 256, …); Fighter fires when (… & 3) == 0; Guardian when (… & 1) == 1
bumpImmunity0 at program start, never reset−1 per frame while > 0 (frame start); set to 8 by a bumpno ram, no peer collision, no satellite pick-up while > 0
tumble, tumbleRates0 at program start, never reset−1 per frame while > 0 (frame start); 0x30 by a bumpforced spin, no velocity control (3)
fireCooldown0 at program start, never resetin playerUpdateauto-fire every 3rd frame
messageTimer0 at level/life start−1 per frame while alive and > 0centre message
deathCountdown0 at program start0x40 at death; −1 per frame in playerDeadScreeninput ignored on the death screen
spawnDir, spawnTypeRot0 at level start+1 after each successful spawnside of appearance, kind rotation
satelliteCounternever (program start: 0)+1 per satellite spawned (a signed 16-bit number: 32767 + 1 wraps to −32768)kind cycle
shot lifetime, explosion ageper object, sections 5–8
other start valuesat program start: keyboard turn rates (pitch, roll, yaw) 0, haveTarget 0, flashColor 0, radar zoom −1; none of them is reset by a level or a new game O
Exact rules: the frame

2. Shared helpers

Everything below is built from these few routines (src/input_math.asm, src/render.c, src/steer.c). Chapter 3 explains the number formats; here are the exact operations.

2.1 Vector arithmetic

dot(a, b):        s = int32(a0*b0 + a1*b1 + a2*b2)             // wraps at 32 bits
                  return int16((s << 2) >> 16)                 // = floor(s / 16384)
cross(a, b):      out0 = h(a1*b2, a2*b1); out1 = h(a2*b0, a0*b2); out2 = h(a0*b1, a1*b0)
   where h(p, q): lo = (p & 0xFFFF) - (q & 0xFFFF); hi = (p >> 16) - (q >> 16)
                  // the borrow of the low-word subtraction is LOST (original quirk):
                  return int16(((hi << 16) | (lo & 0xFFFF)) << 2 >> 16)
rotate(a, toward b, angle):                                     // vec3_rotate
                  k = angle & 2047; s = SIN[k]; c = COS[k]      // Q14 tables, chapter 3
                  for i in 0..2: a[i] = int16((int32(b[i]*s + a[i]*c) << 2) >> 16)
                  e = int16((int32(a0*a0 + a1*a1 + a2*a2) << 1) >> 16) - 0x2000
                  for i in 0..2: if a[i] > 0: a[i] -= e  else if a[i] < 0: a[i] += e
axisShl(q, n):    // vec3_to_lvec3_shl: a Q14 vector into an lvec
                  for each component c: x = (n >= 0) ? c : -c
                                         r = int32(x << |n|)     // bits above 32 lost
                                         result = int64(r)       // sign-extended
axisMul(q, k):    for each component c: result = int64(int32(c * k))

In world units, axisShl(unit axis, n) is 2n−2 units long (n = 8: 64 units, 12: 1024, 16: 16,384) and points backwards for negative n; axisMul(unit axis, k) is k/4 units long.

2.2 Nearness exponents

A relative vector (goal minus body, or object minus you) is turned into a 16-bit direction and an exponent by normalize:

normalize(d, e, limit = 8):              // d: lvec, changed in place; e: exponent, in/out
  while some axis has mid32(d) < -0x4001 or mid32(d) > 0x4000:
      d = d >> 1 (each axis, 64-bit arithmetic shift); e -= 1
  while every axis has -0x2000 <= mid32(d) <= 0x1FFF:
      d = d << 1; e += 1
      if e == limit: stop
  direction = (mid16(d.x), mid16(d.y), mid16(d.z))

Two exponents are used. The steering exponent starts at e = 0. The display exponent distExp is computed by the renderer for every moved body with e starting at the model's scale (1 for ships, aliens, the mutant and the pod; 0 for missiles and satellites). Both say "how near", larger = nearer. The exact meaning, checked by emulating the routine on 200,000 random vectors O:

Exact rules: what an exponent means

Let d be the raw 64-bit difference per axis and k = threshold − start value (display: threshold − scale). Then e ≥ threshold exactly when every axis satisfies −L ≤ d < L, with L = 230−k raw for k ≥ 1 and L = 0x4001 · 216−k raw for k ≤ 0 (and k ≤ 8 − start because of the limit).

kevery axis within (world units)used by
7[−128, 128)satellite touch (display ≥ 7, scale 0), returning pod home (steering ≥ 7); for an alien (scale 1) display 8, where the lock window fails
6[−256, 256)ram (display ≥ 7 with scale 1), missile hits, grab / destroy a pod
4[−1024, 1024)Commander retreat (display ≥ 5)
3[−2048, 2048)Pirate / Fighter retreat (display ≥ 4), brake near a pod
2[−4096, 4096)Guardian arrival
1[−8192, 8192)Pirate may fire, Fighter / Pirate "far enough" (display < 2 is the negation)
0[−16385, 16385) (raw below 0x4001 · 216)Commander "far" (display < 1), missiles giving up (display < 0)
−1[−32770, 32770)Pirate escape (display < 0), satellite lost (display < −1)

"Display ≥ t" for a scale-1 body is row k = t − 1; for a scale-0 body row k = t. A test "< t" is the negation: at least one axis outside. The law holds while every axis difference is below 231 units (mid32 drops the bits above 47).

Worked example. A pod 1000 units straight ahead of an alien along x: the raw difference is (1000 · 65536, 0, 0) = (65,536,000, 0, 0). Steering exponent: 65,536,000 < 230−4 = 67,108,864 but not < 230−5 = 33,554,432, so e = 4 (rows 1–4 hold, row 5 does not). Step by step: the middle value 1000 doubles to 2000, 4000, 8000 (all ≤ 0x1FFF = 8191), then 16000 = 0x3E80 stops the loop after 4 doublings. The display exponent of the same pod seen from you at that distance starts at its scale 1, so it is 1 + 4 = 5.

2.3 Moving and seeing a body

objectMove(o):                                         // object_move
  if o.pitchRate != 0: rotate(o.fwd toward o.up, o.pitchRate);   o.up    = cross(o.fwd, o.right)
  if o.rollRate  != 0: rotate(o.right toward o.up, o.rollRate);  o.up    = cross(o.fwd, o.right)
  if o.yawRate   != 0: rotate(o.fwd toward o.right, o.yawRate);  o.right = cross(o.up, o.fwd)
  if o.speed != 0: o.pos += axisMul(o.fwd, o.speed)    // along the NEW nose
  return see(o)

see(o, noDraw = false):                                // render_object, simulation part
  o.visible = 0
  d = o.pos - shipPos; o.distExp = scale(o.model); normalize(d, o.distExp)
  touch = (o.distExp >= 7 and bumpImmunity == 0)
  o.dir = direction of d
  o.camX = dot(camB, o.dir); o.camY = dot(camC, o.dir); o.camZ = dot(camA, o.dir)
  if o.camZ <= 0x200 or noDraw: return touch
  if o.camZ < o.camX or -o.camZ > o.camX: return touch
  t = int16(o.camY << 1)
  if o.camZ < t or -o.camZ > t: return touch
  o.visible = 1; queue the model for drawing (chapter 9)
  return touch

explosionStep(o):                                      // draw_explosion: age, then draw
  o.distExp += 1
  draw the sparks (chapter 9; it also rewrites o.dir and o.cam* with a down-only
  normalisation, which only drawing uses)

shipPos and camA/camB/camC (forward, right, "up") are your ship's, as playerUpdate left them this frame.

2.4 Steering helpers

All five start the same way O:

aim(b, goal):                                          // shared preamble
  d = goal - b.pos; e = 0; normalize(d, e)
  dir = direction of d
  r = dot(b.right, dir); u = dot(b.up, dir); f = dot(b.fwd, dir)
  b.pitchRate = 0; b.rollRate = 0; b.yawRate = 0
  return e, r, u, f

turnToward(b, r, u):
  p = u >> 7; if p == 0: p = 1
  if p > b.maxTurn: p = b.maxTurn;  if p < -b.maxTurn: p = -b.maxTurn
  y = r >> 7; if y == 0: y = 1
  if y > b.maxTurn: y = b.maxTurn;  if y < -b.maxTurn: y = -b.maxTurn
  b.pitchRate = p; b.yawRate = y

inCone(r, u, w):  return -w < r < w and -w < u < w   // strict

steerChase(b):                         // toward you; returns 1 = "aimed"
  e, r, u, f = aim(b, shipPos)
  if f < 0:
      if b.speed > 200: b.speed -= b.accel
      b.pitchRate = (u < 0) ? -b.maxTurn : b.maxTurn
      return 0
  if inCone(r, u, 0x80):
      if b.speed < b.maxSpeed: b.speed += b.accel
      return 1
  turnToward(b, r, u); return 0

steerFlee(b):                          // away from you; returns nothing
  e, r, u, f = aim(b, shipPos)
  if f > 0:
      if b.speed > 200: b.speed -= b.accel
      b.pitchRate = (u > 0) ? -b.maxTurn : b.maxTurn
      return
  if b.speed < b.maxSpeed: b.speed += b.accel
  if inCone(r, u, 0x80): return
  turnToward(b, r, u); b.yawRate = -b.yawRate; b.pitchRate = -b.pitchRate

steerToObject(b, t):                   // returns the steering exponent
  e, r, u, f = aim(b, t.pos)
  if f < 0:
      if b.speed > 0: b.speed -= b.accel
      b.pitchRate = (u < 0) ? -b.maxTurn : b.maxTurn
      return e
  if inCone(r, u, 0x100):
      if b.speed < b.maxSpeed: b.speed += b.accel
      return e
  turnToward(b, r, u); return e

steerTow(b, t):                        // tail toward t; returns 1 = t dead astern
  e, r, u, f = aim(b, t.pos)
  if f > 0:
      b.pitchRate = (u < 0) ? b.maxTurn : -b.maxTurn
      return 0
  if inCone(r, u, 0x100): return 1
  turnToward(b, r, u); b.pitchRate = -b.pitchRate; b.yawRate = -b.yawRate
  return 0

steerToPoint(b, p):                    // returns e; never changes speed
  e, r, u, f = aim(b, p)
  if f < 0: b.pitchRate = (u < 0) ? -b.maxTurn : b.maxTurn; return e
  if inCone(r, u, 0x100): return e
  turnToward(b, r, u); return e
Exact rules: steering

3. Your ship: playerUpdate

Chapter 4 explains the flying; this is the exact step (src/control.c) O. Screen centre during flight: ox = 320, oy = 175.

playerUpdate():
  // --- 1. steering rates ---
  if mouse enabled:
      pitch = (mouseY - oy + 4) >> 2;  yaw = (mouseX - ox + 4) >> 3;  roll = 0
      if pitch < 0: pitch += 1
      if yaw < 0:   yaw += 1
      if yaw == 0:   (if mouseX > ox: yaw = 1);   (if ox - 8 > mouseX: yaw = -1)
      if pitch == 0: (if mouseY > oy: pitch = 1); (if oy - 8 > mouseY: pitch = -1)
  else:                                         // keyboard: rates persist between frames
      roll = 0
      if pitch == 1 or pitch == -1: pitch = 0
      if yaw == 1 or yaw == -1: yaw = 0
      if Down held:   (if pitch < 0: pitch = 0); (if pitch < 24: pitch += 2)
      elif Up held:   (if pitch > 0: pitch = 0); (if pitch > -24: pitch -= 2)
      else:           (if pitch > 0: pitch -= 2); (if pitch < 0: pitch += 2)
      same for yaw with Right (+) / Left (-)
  if tumble > 0:
      move each of tumbleRates[0..2] one step toward 0
      if mouse enabled: pitch += tR[0]; roll += tR[1]; yaw += tR[2]
      else:             pitch  = tR[0]; roll  = tR[1]; yaw  = tR[2]
  // --- 2. turn the ship (a = forward, b = right, c = "up") ---
  if pitch != 0: rotate(a toward c, pitch); c = cross(a, b)
  if roll  != 0: rotate(b toward c, roll);  c = cross(a, b)
  if yaw   != 0: rotate(a toward b, yaw);   b = cross(c, a)
  // --- 3. radar zoom (one step per key press, latch cleared) ---
  keypad +: zoom = min(zoom + 1, 2);   keypad -: zoom = max(zoom - 1, -6)
  if shields == 0: return                       // dead: no thrust, weapons, cloak, movement
  // --- 4. throttle (32-bit; only its low 16 bits are used below) ---
  if Shift held and throttle < 0x90:  throttle += 8
  if Ctrl held  and throttle > -0x70: throttle -= 8
  // --- 5. guns ---
  if mouseLatch != 0 or SpaceLatch != 0:
      if fireCooldown == 0:
          if cloakOn == 0 or cloakTime == 0: playerFire()      // 7.1
          fireCooldown = 2
      else: fireCooldown -= 1
  if mouse button not held and Space not held:
      mouseLatch = 0; SpaceLatch = 0; fireCooldown = 0
  // --- 6. Enter / Caps Lock, once per press ---
  if EnterLatch or CapsLatch:
      clear both
      if multiplayer: cloakOn = not cloakOn
      else: playerFireMissile()                                // 5.3
  // --- 7. cloak ---
  if cloakTime > 0 and cloakOn: cloakTime -= 1; statusOut = -1
  else: statusOut = 0
  // --- 8. velocity control (body components of the velocity's middle words) ---
  v = (mid16(vel.x), mid16(vel.y), mid16(vel.z))
  vb0 = dot(v, b); vb1 = dot(v, c); vb2 = dot(v, a)
  if tumble == 0:
      if vb0 != 0: n = steps(vb0); vel += (vb0 < 0) ? axisShl(b, n) : axisShl(b, -n)
      if vb1 != 0: n = steps(vb1); vel += (vb1 < 0) ? axisShl(c, n) : axisShl(c, -n)
      want = int16(throttle); if extraThrust != 0: want = want << 1
      if vb2 != want:
          dd = want - vb2; n = steps(dd)
          vel += (dd > 0) ? axisShl(a, n) : axisShl(a, -n)
  // --- 9. move ---
  shipPos += vel                                  // full 64 bits

steps(x):            // the correction is 2^(n-2) units: 0.5 ... 8, or 16 with extra thrust
  n = 1
  if |x| > 2: n += 1;  if |x| > 4: n += 1;  if |x| > 8: n += 1;  if |x| > 16: n += 1
  if extraThrust > 0 and |x| > 32: n += 1; extraThrust -= 1
  return n
Exact rules: your ship

4. Aliens (single player)

Gentle description: chapter 7. Records: 8 alien slots; only slots below alienMax are used by spawning. Type table (src/tables.c) O:

typenamehpmaxSpeed (raw; units = ÷4)maxTurnmissile kindscore
1Pirate2500 up to level index 7, then 500 + 100·(L−7), at most 1000 (set per level)241100
2Fighter270024(1, unused)150
3Guardian4110032(2, unused)200
4Commander / mutant8900322400

4.1 The alien step: aliensUpdate

Per alien, the order is: sense (read last frame's display exponent) → decide (the behaviour switch, which also fires and sets turn rates and speed) → turn and move (objectMove: rotate, then advance along the new nose) → see (new display exponent, touch flag, camera position) → ram → lock mark (src/aliens.c) O.

aliensUpdate():
  haveTarget = 0
  for i in 0..7:                                       // all 8 slots, in order
    a = aliens[i]
    if a.type <= 0: continue
    if a.state == -1:                                  // dying
        a.pos += axisMul(a.fwd, a.speed)               // drifts on at its last speed
        explosionStep(a)
        if a.distExp > 0x40: a.type = 0; aliensLeft -= 1
        continue
    switch a.type:                                     // decide (+ fire)
        1: pirate(a)   2: fighter(a)   3: guardian(a)   4: commander(a)
    touch = objectMove(a)                              // turn, move, see
    if touch and shields > 0:                          // ram
        sound(1); shields -= 1; flashColor = COLLISION
        if shields <= 0: shields = 0; deathCountdown = 0x40
        else: playerBump()                             // 9.1 (sets bumpImmunity = 8)
        a.hp -= 1
        if a.hp == 0: a.state = -1; a.distExp = scale(a.model)   // = 1; no points
    lim = (a.distExp >= 0) ? int16(0xC0 << a.distExp) : (0xC0 >> -a.distExp)
    if a.camZ > 0 and -lim < a.camY < lim and -lim < a.camX < lim:
        haveTarget = 1; a.visible = 2                  // lock mark
Exact rules: the alien step

4.2 Spawning: alienSpawn and the level budget

levelSetup(L):                       // L = level index, 0 for level 1 (main, before the intro)
  if (L & 3) == 0: podsReset()          // 6.1
  podsPlace()
  alienMax = (L > 12) ? min(L - 8, 8) : 4
  counts = [8, 2L, (L > 1) ? 2(L-1) : 0, (L > 3) ? 2(L-3) : 0]
  TYPES[0].maxSpeed = (L > 7) ? min((L-7)*100 + 500, 1000) : 500
  each count = min(count, 8); aliensLeft = sum(counts)
  if podsLeft == 0: counts = [0, 0, 0, aliensLeft]      // whole wave: type 4 (mutants)
  spawnDir = 0; spawnTypeRot = 0

alienSpawn():                        // frames with (frameCount & 63) == 0
  i = first slot in 0 .. alienMax-1 with aliens[i].type == 0;  none: return
  a = aliens[i]; a.target = none
  k = first k in 0..3 with counts[(k + spawnTypeRot) & 3] > 0;  none: return
  t = (k + spawnTypeRot) & 3
  counts[t] -= 1                                       // used even if it becomes a mutant
  if podsLeft == 0:  a.type = 4; a.state = 4; a.model = MUTANT; t = 3
  else:              a.type = t + 1; a.model = TYPES[t].model; a.state = 0
  a.maxSpeed = TYPES[t].maxSpeed; a.speed = a.maxSpeed; a.accel = 0
  a.maxTurn = TYPES[t].maxTurn; a.hp = TYPES[t].hp; a.distExp = 0
  a.particles = explosionParticles                     // 12 Lines / 38 Polygons; drawing only
  a.pos = shipPos + [axisShl(camB, 16), axisShl(camB, -16),
                     axisShl(camC, 16), axisShl(camC, -16)][spawnDir & 3]
  spawnDir += 1; spawnTypeRot += 1
Exact rules: spawning and what a slot keeps

4.3 Pirate (type 1, ai_abductor)

0 attacksteerChase 1 retreatsteerFlee 2 approachsteerToObject(pod) 3 turnsteerTow(pod) 4 escapestraight, +50/frame gonealien + pod removed aimed ∧ D≥2 ∧ missilelaunched, or D≥4 D<2 ∧ free pod:claim it D<2 ∧ no free pod S≥6: grab,speed 0 pod deadastern D<0 from 2, 3 or 4: its pod has state −1 (destroyed) → attack D = display exponent (to you, previous frame). S = steering exponent (to the pod, this frame).
The Pirate. The red dashed edge is taken from approach, turn or escape when the pod was destroyed.
pirate(a):
  switch a.state:
  0:  // attack
      if steerChase(a) == 1 and a.distExp >= 2 and enemyMissileLaunch(a) == 1:
          a.state = 1         // steerChase always runs; the launch only if the two tests before it hold
      if a.distExp > 3: a.state = 1
  1:  // retreat
      steerFlee(a)
      if a.distExp >= 2: break
      p = first pod j in 0..5 with pods[j].state == 0 and pods[j].type > 0
      if none: a.state = 0; break
      a.target = p; p.state = 1; p.target = a; a.state = 2      // claim
  2:  // approach
      if a.target.state == -1: a.state = 0; break               // no steering this frame
      s = steerToObject(a, a.target)
      if s >= 3 and a.speed > 200: a.speed -= 50
      if s < 6: break
      a.speed = 0; a.state = 3; a.target.state = 2               // grab: the pod is towed
      message("WARNING: POD IN DANGER", 0x10); sound(3)
  3:  // turn
      if a.target.state == -1: a.state = 0; break
      if steerTow(a, a.target) == 1: a.state = 4
  4:  // escape
      if a.target.state == -1: a.state = 0; break
      if a.speed < a.maxSpeed: a.speed += 50
      a.yawRate = 0; a.pitchRate = 0                             // roll stays as left (0)
      if a.distExp >= 0: break
      a.type = 0; aliensLeft -= 1                                // escaped: no explosion
      a.target.type = 0; podsLeft -= 1
      message("POD DESTROYED", 0x10)
TransitionCondition (priority)New state actsThis frame's motion
0 → 1aimed and D ≥ 2 and a missile slot free (missile launched); or D ≥ 4. Both lead to 1next framechase rates
1 → 2D < 2 and a pod with state 0 and type > 0 exists (lowest index)next frameflee rates
1 → 0D < 2 and no such podnext frameflee rates
2/3/4 → 0the pod's state is −1; tested first in each of these statesnext framelast frame's rates and speed (no helper called)
2 → 3steering exponent to the pod ≥ 6next frameturns with this frame's rates, does not move (speed 0)
3 → 4steerTow reports the pod within the ±256 cone behindnext framerates 0 (the helper returned from the cone)
4 → goneD < 0 (some axis 32,770 units or more from you, as of the previous frame; row k = −1 of 2.2)at oncemoved and seen once more (4.1)
Exact rules: Pirate

4.4 Fighter (type 2, ai_fighter)

0 attackchase; aimed ∧ frame%4=0: laser 1 retreatsteerFlee D≥4 (flees in the SAME frame) D<2 (acts next frame)
The Fighter: passes at you.
fighter(a):
  switch a.state:
  0:  if steerChase(a) == 1 and (frameCount & 3) == 0: alienFire(a)   // 7.4
      if a.distExp < 4: break
      a.state = 1
      // falls through into state 1 in the same frame
  1:  steerFlee(a)                                // overwrites the chase rates
      if a.distExp < 2: a.state = 0
Exact rules: Fighter

4.5 Guardian (type 3, ai_turret)

0 travelsteerToPoint(origin); S≥2: −100/frame 1 turret (for ever)chase (speed 0); aimed ∧ odd frame: laser S≥2 and speed already 0 (speed 1100 → 0 takes 11 braking frames, the switch is the 12th)
The Guardian flies to the world origin, the centre of the pod field, and stays.
guardian(a):
  switch a.state:
  0:  s = steerToPoint(a, (0,0,0))              // the "rally point", always the origin
      if s >= 2:
          if a.speed > 0: a.speed -= 100
          else: a.speed = 0; a.state = 1
      else: a.speed = a.maxSpeed                // drifted out again: full speed
  1:  if steerChase(a) == 1 and (frameCount & 1) == 1: alienFire(a)
Exact rules: Guardian

4.6 Commander and mutant (type 4, ai_pod_killer)

0 attacksteerChase 1 retreatsteerFlee 2 pick a podno steering call 3 approachsteerToObject(pod) 4 mutantchase, accel 0x32;aimed: laser every frame aimed (missile if aslot is free) or D≥5 D<1 free pod:claim no free pod S≥6: pod destroyed,speed 0, mutant model pod already state −1 → attack spawned while podsLeft == 0: starts here (type 4, state 4)
The Commander. A mutant is a type-4 alien in state 4.
commander(a):
  switch a.state:
  0:  if steerChase(a) == 1:
          enemyMissileLaunch(a)                 // kind 2; result ignored
          a.state = 1
      if a.distExp >= 5: a.state = 1
  1:  steerFlee(a)
      if a.distExp < 1: a.state = 2
  2:  p = first pod j in 0..5 with pods[j].state == 0 and pods[j].type > 0
      if none: a.state = 0; break
      a.state = 3; a.target = p; p.state = 1; p.target = a
  3:  if a.target.state == -1: a.state = 0; break
      s = steerToObject(a, a.target)
      if s >= 3 and a.speed > 200: a.speed -= 100
      if s < 6: break
      a.speed = 0; a.state = 4
      a.target.state = -1                       // pod explodes; its age = its current distExp
      a.model = MUTANT; podsLeft -= 1
      message("POD DESTROYED", 0x10); sound(0)
  4:  a.accel = 0x32
      if steerChase(a) == 1: alienFire(a)
TransitionConditionNew state actsThis frame's motion
0 → 1aimed (a missile is launched if one of the 4 slots is free); or D ≥ 5next framechase rates
1 → 2D < 1next frameflee rates
2 → 3 / 2 → 0a free pod exists / nonenext framethe flee rates and speed of the previous frame, again
3 → 0its pod has state −1next framelast frame's rates and speed
3 → 4steering exponent to the pod ≥ 6next frameturns with this frame's rates, speed 0
Exact rules: Commander and mutant

4.7 Death, escape and removal of aliens

CauseWhere in the frameEffectExplosion age starts
your laser, hp reaches ≤ 0playerShotsUpdate, before the aliens movestate −1, score added, sound 01
ram, hp reaches 0aliensUpdate after its movestate −1, no scoremodel scale = 1
your missileplayerMissilesUpdatehp −16 (always fatal), state −1, scoremodel scale = 1
Pirate escapeits behaviourtype 0 at once, aliensLeft − 1—

A dying alien (state −1) is skipped by your shots, missiles and the lock window; each frame it drifts along its old nose at its last speed, its age goes up by 1, and when the age exceeds 0x40 the slot is freed and aliensLeft drops by 1 O.

5. Missiles

Four slots for the aliens' missiles, four for yours (src/aliens.c, src/missiles.c). Missile models have scale 0.

5.1 Enemy launch: enemyMissileLaunch(a)

enemyMissileLaunch(a):
  m = first of the 4 enemy slots with type == 0;  none: return 0
  m.pos = a.pos; m.fwd = a.fwd; m.right = a.right; m.up = a.up     // before a's move this frame
  m.type = TYPES[a.type - 1].missileKind        // Pirate 1, Commander 2
  m.distExp = 0; m.state = 0; m.particles = 12
  if m.type == 1: m.accel = 0;    m.maxTurn = 8;    model = MISSILE_0
  else:           m.accel = 0x32; m.maxTurn = 0x20; model = MISSILE_1
  m.maxSpeed = 0x640; m.speed = 0x640           // 400 units per frame
  message("WARNING: MISSILE LAUNCH DETECTED", 0x10); sound(3)
  return 1

5.2 Enemy flight and hit: enemyMissilesUpdate

enemyMissilesUpdate():
  for each enemy slot m in order:
    if m.type <= 0: continue
    if m.state == -1:
        explosionStep(m); if m.distExp > 0x40: m.type = 0
        continue                                 // an exploding missile does not move
    steerChase(m)                                // toward you, even if you are dead
    objectMove(m)                                // its touch flag is ignored
    if m.distExp < 0 and m.type == 1: m.type = 0     // kind 1 gives up
    if m.distExp >= 6 and shields > 0:              // hit you
        sound(1); shields -= 1; flashColor = HIT
        if shields <= 0: shields = 0; deathCountdown = 0x40
        m.state = -1; m.distExp = 0

5.3 Your launch: playerFireMissile (Enter / Caps Lock, single player)

playerFireMissile():
  if haveTarget == 0: message("No Target", 0x10); return    // previous frame's lock
  if missiles == 0: return
  m = first of your 4 slots with type == 0;  none: return   // stock not used
  missiles -= 1; message("Missile Launched", 0x10)
  m.pos = shipPos + axisShl(camC, 8)            // 64 units along "up", before your move
  m.fwd = camA; m.right = camB; m.up = camC
  m.type = 1; m.distExp = 0; m.state = 1; m.particles = 12
  m.speed = 0x640; m.maxSpeed = 0x640; m.accel = 0x64; m.maxTurn = 0x80
  m.model = PLAYER_MISSILE                       // scale 0
  m.target = none
  for i in 0..7:                                 // FIRST marked alien, not the nearest
    if aliens[i].type > 0 and aliens[i].state != -1 and aliens[i].visible == 2:
        m.target = aliens[i]; m.state = 0; break

5.4 Your missile's flight: playerMissilesUpdate

playerMissilesUpdate():
  i = 0
  while i < 4:
    m = yours[i]
    if m.type <= 0: i += 1; continue
    switch m.state:
    -1: explosionStep(m); if m.distExp > 0x40: m.type = 0
        i += 1; continue                         // no movement
    0:  t = m.target
        if t.state == -1 or t.type == 0: m.state = 1; break      // unguided from now; this
                                                 // frame it still turns with last frame's rates
        e = steerToObject(m, t)                  // brakes 25/frame to 0 if t is behind
        if e >= 6:                               // contact: every axis within 256 units
            t.hp -= 16
            if t.hp <= 0: t.hp = 0; t.state = -1; t.distExp = scale(t.model)
                          addScore(TYPES[t.type - 1].score)
            m.state = -1; m.distExp = 1
            sound(0)
            continue                             // WITHOUT i += 1: the same slot again, now
                                                 // in case -1: explosionStep ages it to 2,
                                                 // it does not move this frame
        break                                    // no hit: objectMove below
    1:  m.yawRate = 0; m.pitchRate = 0
        if m.distExp < 0: m.type = 0             // previous frame's exponent
    objectMove(m)                                // also runs once for a missile just expired
    i += 1
Exact rules: missiles

6. Pods

Six pod records (src/pods.c); target links a pod and the alien that claimed it in both directions. Pod model scale 1.

0 idlespin 0x20, speed 0 1 claimedkeeps spinning 2 towedfollows its captor 3 returninghome at 200 raw −1 explodingfreed at age ≥ 0x40 removedPirate escaped alien claims claimer dying Pirate grabs captor dying home: S≥7 any state ≥ 0 → −1: hit by your laser, or reached by its Commander (from 1)
Pod states. A pod is lost (podsLeft − 1) on the way into "exploding" or "removed".

6.1 Placement and counting

podsReset():  for each pod: pod.type = 1;   podsLeft = 6     // new game and level index L&3==0

podsPlace():                                   // every level start, after podsReset
  for j in 0..5:
    p = pods[j]; if p.type <= 0: continue      // lost pods stay lost
    p.fwd = (0,0,0x4000); p.up = (0,0x4000,0); p.right = (0x4000,0,0)
    p.pos = axisMul(p.right, PX[j]) + axisMul(p.up, PY[j]) + axisMul(p.fwd, PZ[j])
    p.home = p.pos
    p.state = 0; p.model = POD; p.maxTurn = 0x80; p.accel = 0; p.speed = 0
    p.particles = explosionParticles
// PX = [-4000, 0, 4000, 0, 0, 0], PY = [0, 0, 0, 0, -4000, 4000], PZ = [0, -4000, 0, 4000, 0, 0]
// i.e. pods at x = -1000, z = -1000, x = +1000, z = +1000, y = -1000, y = +1000 units

podsLeft goes down by 1 when your laser hits a pod, when a Commander reaches its pod, and when a Pirate escapes with one. Nothing else changes it until the next podsReset O.

6.2 The pod step: podsUpdate

podsUpdate():
  for j in 0..5:
    p = pods[j]; if p.type == 0: continue
    switch p.state:
    -1: explosionStep(p); if p.distExp >= 0x40: p.type = 0      // note: >=, not >
        continue
    0:  p.rollRate = 0x20; p.pitchRate = 0x20; p.yawRate = 0; p.speed = 0
    1:  if p.target.state == -1: p.state = 0                   // claimer is dying
    2:  if p.target.state == -1: p.state = 3                   // captor is dying...
        steerToObject(p, p.target)                             // ...but still follow it now
        p.speed = p.target.speed
    3:  e = steerToPoint(p, p.home); p.speed = 200
        if e >= 7: p.state = 0; p.speed = 0                    // every axis within 128 of home
    objectMove(p)                                              // touch flag ignored
Exact rules: pods

7. Shots

Records: 8 slots for your shots, 8 shared by all aliens, 8 per peer for copies of other players' shots (src/shots.c, src/pods.c, src/players.c).

7.1 Firing: playerFire

playerFire():
  if spectator: return
  i = first of your 8 slots with state == 0;  none: return
  s.pos = shipPos + axisShl(camC, 8)            // 64 units along "up"
  s.fwd = camA; s.right = camB; s.up = camC
  s.state = 0x18; myShots[i] = 1                // 24 frames
  if firePower > 0: firePower -= 1; s.state |= 0x100; myShots[i] = 2   // powered
  s.vel = shipVel + axisShl(camA, 12)           // your velocity + 1024 units forward
  sound(5)

State word: 0 free; low byte = frames left; bit 0x100 = powered; negative = exploding (counts up from −8). myShots[i] is the network flag: 0 free, 1 flying, 2 flying powered, 3 exploding.

7.2 Your shots each frame: playerShotsUpdate

playerShotsUpdate():
  eventOut[0..2] = 0; itemEventOut = 0           // last frame's reports are gone
  for i in 0..7:
    s = shots[i]
    if (s.state & 0xFF) == 0: s.state = 0; myShots[i] = 0; continue     // expired / free
    if int16(s.state) < 0:                       // exploding
        myShots[i] = 3; s.state += 1
        if int16(s.state) < 0: draw the ring
        continue
    s.state -= 1; s.pos += s.vel; draw the shot
    if multiplayer:
        for j in 0..2:                           // peer ships
            q = peerShips[j]
            if q.state != -1 and q.type != 0 and shotHits(s, q):
                eventOut[j] = peerSlot[j] + 1
                if (s.state & 0x100) != 0: eventOut[j] += 0x100
                s.state = 0xFFF8; addScore(50); break
        for j in 0..2:                           // peer satellites: NO break
            if peerItems[j].type > 0 and shotHits(s, peerItems[j]):
                s.state = 0xFFF8; itemEventOut = peerSlot[j] + 0x101; sound(0)
    else:
        for j in 0..7:                           // 1. aliens
            o = aliens[j]
            if o.type > 0 and o.state >= 0 and shotHits(s, o):
                s.state = 0xFFF8; o.hp -= 1
                if firePower > 0: o.hp -= 1       // the STOCK now, not the shot's bit
                if o.hp <= 0: o.state = -1; o.distExp = 1
                              addScore(TYPES[o.type - 1].score); sound(0)
                break
        if an alien was hit: continue
        for j in 0..3:                           // 2. enemy missiles
            o = enemyMissiles[j]
            if o.type > 0 and o.state >= 0 and shotHits(s, o):
                s.state = 0xFFF8; o.state = -1; o.distExp = 0; addScore(25); sound(0); break
        if a missile was hit: continue
        for j in 0..5:                           // 3. pods (friendly fire)
            o = pods[j]
            if o.type > 0 and o.state >= 0 and shotHits(s, o):
                s.state = 0xFFF8; o.state = -1; o.distExp = 0; podsLeft -= 1; sound(0); break
        if a pod was hit: continue
    if myItem.type > 0 and shotHits(s, myItem): // 4. own satellite (always in multiplayer)
        myItem.type = -1; myItem.distExp = 0; sound(0); s.state = 0xFFF8

7.3 The hit test: shotHits(s, o)

shotHits(s, o):
  sc = scale(o.model)                            // 1: aliens, pods, ships; 0: missiles, satellites
  r = 0x200; if sc > 1: r = int16(r << (sc - 1))
  h = int16(0x60 << sc)                          // 0xC0 for scale 1, 0x60 for scale 0
  d = o.pos - s.pos
  for each axis: m = mid32(d.axis); if m > r or m < -r: return false
  v = (mid16(d.x), mid16(d.y), mid16(d.z))       // exact: the first test bounded them
  dr = dot(v, s.right); du = dot(v, s.up); df = dot(v, s.fwd)
  if df > r or df < -r: return false
  if dr > h or dr < -h: return false
  if du > h or du < -h: return false
  return true

7.4 Alien laser: alienFire(a)

alienFire(a):                                    // Fighter, Guardian, mutant
  s = first of the 8 alien-shot slots with state == 0;  none: return
  s.pos = a.pos; s.fwd = a.fwd; s.right = a.right; s.up = a.up   // before a's turn and move
  s.state = 0x18

7.5 Alien shots each frame: alienShotsUpdate

alienShotsUpdate():
  for each alien shot s in order:
    if s.state == 0: continue
    s.state -= 1                                 // reaching 0 frees it after this frame's test
    s.pos += axisShl(s.fwd, 12)                  // 1024 units along its nose, no inherited speed
    draw it
    if shields == 0: continue
    d = shipPos - s.pos
    for each axis: if mid32(d.axis) > 0x400 or mid32(d.axis) < -0x400: skip to next shot
    v = mid16 of each axis
    a = dot(v, s.fwd); u = dot(v, s.up); r = dot(v, s.right)
    if r > 0x400 or r < -0x400 or a > 0x100 or a < -0x100 or u > 0x100 or u < -0x100: continue
    sound(1); flashColor = HIT; s.state = 0
    shields -= 1; if shields == 0: deathCountdown = 0x40
Exact rules: shots

8. Satellites

One own satellite record (myItem) and, in multiplayer, one copy per peer (src/satellite.c). Kinds: 1 shields, 2 missiles (multiplayer: cloak), 3 extra thrust, 4 fire power; type −1 = exploding. Model scale 0.

8.1 Spawning

satellitesClear():                // level start / life start
  myItem.type = 0; myItem.fwd = (0,0,0x4000); myItem.right = (0x4000,0,0); myItem.up = (0,0x4000,0)
  myItem.particles = 12
  for each peer copy: type = 0, model = SAT_SHIELDS, same axes, particles 12

satelliteSpawn():                 // frames with (frameCount & 127) == 0, not for spectators
  if myItem.type != 0: return     // also while it explodes
  satelliteCounter += 1                          // 16-bit signed, wraps
  myItem.pos = 0
  mid(myItem.pos.x) = rand() * 20000 / 32768     // in this order: x, y, z
  mid(myItem.pos.y) = rand() * 20000 / 32768
  mid(myItem.pos.z) = rand() * 20000 / 32768
  myItem.pos -= (10000, 10000, 10000) units      // 64-bit: −10000 … 9999 around the ORIGIN
  switch satelliteCounter & 3:
    0: type 2 (model: cloak in multiplayer, missiles in single player)
    1: type 3    2: type 4    3: type 1

8.2 The satellite step: satelliteUpdate

satelliteUpdate():
  if multiplayer:                                          // 1. did a peer take / shoot mine?
    for each peer i:
      if (peerEvents[i][4] & 0xFF) == playerIndex + 1:
          if (peerEvents[i][4] & 0x100) != 0: myItem.type = -1; myItem.distExp = 0   // shot
          else: myItem.type = 0                                               // collected
  if myItem.type != 0:                                     // 2. my own satellite
    if myItem.type > 0:
        rotate(myItem.fwd toward myItem.right, 0x20); myItem.right = cross(myItem.up, myItem.fwd)
        touch = see(myItem)
        if not multiplayer and myItem.distExp < -1: myItem.type = 0       // lost far away
        if touch and not spectator: applyPickup(myItem.type); myItem.type = 0
    else:
        explosionStep(myItem); if myItem.distExp > 0x40: myItem.type = 0; myItem.distExp = 0
  if multiplayer:                                          // 3. the peers' satellites
    for each peer i:
      c = peerItems[i]; if c.type == 0: continue
      if peerAlive[i] == 0: c.type = 0; continue
      if c.type > 0:
          c.state = 0; c.model = SAT_MODEL[c.type]
          rotate(c.fwd toward c.up, 0x20); c.up = cross(c.fwd, c.right)
          if see(c) and not spectator:
              applyPickup(c.type); itemEventOut = peerSlot[i] + 1
      else:
          if c.state == 0: c.state = 1; c.distExp = 0     // start the explosion once
          explosionStep(c)                                 // never freed here

applyPickup(kind):
  messageTimer = 0x20
  if multiplayer: shields = 0x20; message "SHIELDS RESTORED"
  kind 1: single: shields = min(shields + 8, 0x20), "EXTRA SHIELDS"
  kind 2: multi: cloakTime = 0x200; cloakOn = 0        single: missiles = min(missiles + 3, 0x20), "MISSILES"
  kind 3: multi: extraThrust = 0x400                   single: min(extraThrust + 0x400, 0x1000), "EXTRA THRUST"
  kind 4: multi: firePower = 0x40                      single: min(firePower + 0x40, 0x100), "EXTRA FIRE POWER"
  sound(2)
Exact rules: satellites

9. Contacts, damage, death and the level

9.1 Every way your shields change, in frame order

StepEventShieldsFlashBumpAt 0
aliensUpdatean alien touches you (display ≥ 7, immunity 0)−1collisionyes, if still > 0countdown 0x40
enemyMissilesUpdatemissile display ≥ 6−1hitnocountdown
alienShotsUpdateslab test−1hitnocountdown (only at exactly 0)
satelliteUpdatepick-up+8 (max 32) / multiplayer = 32———
remotePlayersUpdatea peer ship touches you−1collision (via the bump)yes, if still > 0status 1, killer = slot + 4, countdown
netSyncFramea peer's hit report for your slot−1 (−2 powered)hit / powered hitnostatus 1, killer = slot, countdown
level transitionlevel completed+8 (max 32)
playerBump():                                   // players.c
  bumpImmunity = 8; tumble = 0x30; flashColor = COLLISION
  message("COLLISION", 0x30)
  tumbleRates[0] = (rand() * 2 / 32768) * 0x60 - 0x30      // pitch, first rand()
  tumbleRates[1] = (rand() * 2 / 32768) * 0x60 - 0x30      // roll, second rand()
  tumbleRates[2] = 0
  shipVel = PRESET[playerIndex]   // slot 0: (0,0,+64), 1: (0,0,-64), 2: (0,+64,0), 3: (0,-64,0) units/frame
Exact rules: damage

9.2 Score

addScore(points):                               // 32-bit
  score[me] += points
  if score[me] > 1000000: score[me] -= 1000000
  scoreText = format("SCORE: %6ld", score[me])

Points: alien killed by laser or missile: its type's score (a mutant 400); enemy missile shot down: 25; level bonus; multiplayer: 50 per laser hit on a peer. Rams, pods and satellites give nothing O.

9.3 Death: playerDeadScreen

Called in place of the radar and instruments in every frame with shields 0; the world keeps running (src/screens.c) O.

playerDeadScreen():
  draw "Game Over" (single) / "You were killed by <name of slot killerIndex & 3>" (multi)
  if deathCountdown > 0:
      clear the Enter latch and the mouse latch; deathCountdown -= 1; return 0
  if single player and score[0] > lowest high score:
      shields = 0x20; return 1                   // straight to initials entry
  draw "Press ENTER to restart"
  if neither Enter nor mouse latched: return 0
  shields = 0x20; sound(4); clear both latches
  if single player: return 1                     // ends the flight loop
  // multiplayer respawn, inside the loop:
  throttle = 0; statusOut = 0; cloakTime = 0; cloakOn = 0; firePower = 0; extraThrust = 0
  shipPos += axisShl(camC, 12)                   // 1024 units along "up"
  return 0                                       // velocity is NOT reset: the new life keeps the
                                                 // velocity from before death (a dead ship only
                                                 // stopped moving because playerUpdate returned early)

9.4 After the single-player loop, and the level transition

after the flight loop (single player):
  if shields == 0: new game                      // ESC pressed while dead
  if aliensLeft > 0: new game                    // ESC, or a death (shields already 32 again)
  if levelComplete() == ESC: new game
  goto level start

levelComplete():
  addScore((level + 1) * podsLeft * 1000)        // 32-bit; podsLeft as it is now
  shields = min(shields + 8, 0x20)
  ship: axes = identity (a = +z, b = +x, c = +y), position 0, velocity 0
  wait for Enter (level += 1) or ESC

level start (single player):
  explosionParticles = wireframe ? 12 : 38
  levelSetup(level)                              // 4.2: pods, budget, Pirate speed, rotations
  levelIntro()                                   // ESC: new game. This screen ROLLS the camera
  throttle = 0
  aliensClear()                                  // 8 alien slots + 8 missile slots
  satellitesClear()
  frameCount = 0; messageTimer = 0
  capture the keyboard; clear the ESC latch
  enter the flight loop

new game (single player):
  attract screens, start-level menu (level 0..7)
  score[me] = 0; missiles = 16; firePower = 0; extraThrust = 0; cloak = 0
  ship: identity axes, position 0, velocity 0, throttle 0, shields 32
  podsReset(); then "level start"
Exact rules: level end and transition

10. Multiplayer: the local step around the network

What one machine does with the other players (src/net.c, src/players.c). Chapter 8 explains the design; the packet layout is in chapter 8 and docs/network-protocol.md. Peers are numbered 0–2 (a spectator: 0–3); peerSlot[i] is the slot (0–3) of peer i.

10.1 Sending and receiving

postPeerListens():    for each peer i with peerAlive[i] != 0: arm the receive for peer i
sendStateIfIdle():    if the previous send has finished: broadcast
                        { name, camA/camB/camC, shipPos, shipVel, eventOut[0..2], statusOut,
                          itemEventOut, score[me], myItem.type + myItem.pos, myShots[0..7] }

on receive from peer i (at most one per armed receive):
  name    -> names[peerSlot[i]]          axes -> peerShips[i].fwd/right/up
  pos     -> peerShips[i].pos            vel  -> peerShips[i].home   (used for shot copies)
  events  -> peerEvents[i][0..4]         score -> score[peerSlot[i]]
  item    -> peerItems[i].type, .pos     shot flags -> peerShots[i][0..7]

In the original a packet is written into these records the moment it arrives, at any point between postPeerListens and the end of netSyncFrame's wait O. A rebuild that wants determinism should apply each received packet at one fixed point; applying it just before step 3 of netSyncFrame matches the common case (design proposal, not the original).

10.2 The other ships: remotePlayersUpdate

remotePlayersUpdate():
  for each peer i:
    q = peerShips[i]
    if q.type == 0: continue
    if peerEvents[i][3] == 2: continue                 // peer not in play
    if peerAlive[i] == 0: q.type = 0; continue
    if q.state == -1:                                  // killed (started by netSyncFrame)
        if q.distExp == 3:
            message("<name> has been killed", 0x40); sound(0)
        explosionStep(q)
        if q.distExp > 0x40: q.state = 0; q.type = 0
        continue
    touch = see(q, noDraw = (peerEvents[i][3] == -1))  // cloaked: not drawn, still touches
    if touch and shields > 0 and not spectator:
        shields -= 1
        if shields == 0: statusOut = 1; killerIndex = peerSlot[i] + 4; deathCountdown = 0x40
        else: playerBump()

10.3 Copies of their shots: remoteShotsUpdate

remoteShotsUpdate():
  for each peer i (same presence tests as above: type != 0, status != 2):
    for k in 0..7:
      s = copies[i][k]; f = peerShots[i][k]
      if s.state == 0 or f == 4:
          if f == 0 or f == 3: continue
          s.pos = peerShips[i].pos + axisShl(peerShips[i].up, 8)
          s.state = 0x18; if f == 2: s.state |= 0x100
          s.vel = peerShips[i].home + axisShl(peerShips[i].fwd, 12)
      s.state -= 1                                     // 16-bit
      if int16(s.state) >= 0:
          if f == 3: s.state = 0xFFF9                  // explosion ring
          else: s.pos += s.vel
      else: s.state += 1                               // exploding copies stay as they are
      if s.state != 0: draw it
      if f == 0: s.state = 0

Copies never hit anything; the shooter's machine decides hits (7.2) O.

10.4 The end of the frame: netSyncFrame

netSyncFrame():
  // 1. wait
  while tick < 5 and some peer i in 0..3 has peerAlive[i] != 0 and its receive still pending: wait
  // 2. liveness
  for each peer i:
    if peerAlive[i] != 0 and receive pending:
        if peerAlive[i] > 0: peerAlive[i] -= 1
        if peerAlive[i] > 0: cancel the receive (re-armed next frame)
    elif peerAlive[i] < 4 and receive completed: peerAlive[i] = 4
  for each peer i:
    // 3. hits on me (reads the LAST packet of peer i, new or not)
    if not spectator:
      for j in 0..2:
        w = peerEvents[i][j]
        if (w & 0xFF) == playerIndex + 1:
            sound(1)
            if (w & 0x100) != 0: shields -= 2; flashColor = POWERED_HIT
            else:         shields -= 1; flashColor = HIT
            if shields <= 0: shields = 0; statusOut = 1; killerIndex = peerSlot[i]; deathCountdown = 0x40
            if cloakTime > 0: cloakTime = 0; message("Cloak Destroyed!", 0x30)
    // 4. peer status
    st = int16(peerEvents[i][3])
    if st == 1 and peerShips[i].state == 0: peerShips[i].state = -1; peerShips[i].distExp = 3
    if st <= 0 and peerShips[i].type == 0 and peerAlive[i] != 0:
        peerShips[i].state = 0; peerShips[i].type = 1
    if st == 2: peerShips[i].type = 0; peerShips[i].state = 0
Exact rules: multiplayer local step
Quirks a faithful rebuild keeps
For a rebuild

Write one function per heading of this chapter and call them in the order of 1.1 (single player) or 1.2 (multiplayer). Use 64-bit integers for positions (BigInt or a pair of 32-bit numbers in JavaScript), the exact dot, rotate and cross of 2.1 (with the lost borrow) and the exponent rule of 2.2: then every threshold, every turn and every hit lands on the same frame as in the original. Test a few frames against chapter 21's reference cases before adding drawing.