How NetWars Works Chapter 2 of 13, plus appendices

2. The program as a loop

A game is not a program that runs once from top to bottom. It is a loop that draws a new picture many times a second, and between pictures moves everything a little. This chapter shows NetWars' loops: the big one between screens, the small one inside each screen, and the clock that sets their pace.

Screens are states

At any moment NetWars is on exactly one screen: the title, a menu, the flight, the high-score table. Each screen knows which keys lead to which other screen. Programmers call this a state machine: a set of states and the rules for moving between them. The picture below is the whole of NetWars at this level (from src/main.c).

Title menu Esc → quit to DOS SINGLE PLAYER MULTIPLAYER Instructions ⇄ high scores (initials entry first after a top-ten game) Select start level 1–8 Level introduction Flight Level n completed Game Over (drawn over the flight) Single Player Enter Enter Enter all aliens destroyed Enter: next level shields 0 Enter (automatic after a top-ten score) Esc (score 0) Esc Esc Multi Player Lobby: pick a slot or spectate; Universe menu Type your name (also the score board) Flight "You were killed by …" (over the flight) Flight (spectating) Enter on a free slot Enter Esc (new life, score 0) shields 0 Enter: respawn Esc Spectate Esc → lobby Esc
The screens of NetWars and the main ways between them. Red boxes are the flight screen; "Game Over" and "You were killed" are text drawn over the still running flight. Esc almost always means "back". Not shown: Esc from the level introduction or "Level completed" returns to the instructions; the pull-down menus and the help page (F1) are reachable from most non-flight screens.

Two details matter for a faithful rebuild:

Inside a screen: one frame after another

Almost every screen, even the title with its spinning logo, is itself a loop. Each pass draws one complete picture, a frame, and checks the keyboard. A menu simply redraws itself, frame after frame, until a key changes the state. (The one exception is the F1 help page, which is drawn once and then waits for a key.)

To avoid flicker the game uses two pictures (the graphics card holds two "pages" of video memory). It draws the next frame on the hidden page while the other one is on screen, then swaps them in one instant. The swap waits for the moment the monitor has finished painting the screen from top to bottom (the vertical retrace, about 70 times a second on VGA), so the swap never happens halfway through the monitor's sweep. This is called double buffering.

The flight frame, step by step

The flight screen is where the game happens. One flight frame does the following, in this order (all from the flight loop in src/main.c):

  1. Esc? Leave the loop; your score becomes 0 (spectators have none).
  2. Multiplayer: network. Get ready to receive this frame's packets from the other players, and send this machine's state packet: a small message with your position, orientation, status and events (chapter 8). Spectators never send.
    Single player: level cleared? If every alien of the wave is gone and the ship is alive, leave the loop.
  3. Start the frame's clock (tick counter = 0) and show the picture drawn in the previous frame (swap pages, waiting for the retrace). So the picture you see is always one frame behind the simulation.
  4. Pause: F2 freezes a single-player game until F2 again. In multiplayer the key is ignored, because the other players cannot be paused.
  5. Count: the frame counter goes up by one; two short timers that follow a collision count down (chapter 6).
  6. Clear the hidden page to black, or to a flash colour for one frame after a hit.
  7. Simulate and collect, in this order:
    • your ship (steering, throttle, firing, moving);
    • your laser shots (moving, hitting);
    • single player: every 64th frame a new alien, if one of its places is free and the level still has aliens to send; then the aliens, the aliens' missiles, your missiles, the pods, the aliens' laser shots;
    • multiplayer: the other players' ships and shots, as last received;
    • every 128th frame a new satellite if you have none (not for spectators); then the satellites.
    As each object is moved it is also prepared for drawing: its faces (the flat polygons its model is made of) are put into the frame's draw list (chapter 9). So simulation and drawing are interleaved, object by object.
  8. Draw: the stars, then the draw list, faces far from you first and near ones last; then the score; then the radar and instruments and any message, or the death text if shields are 0.
  9. Wait before the next frame:
    • single player: until the next timer tick (if step 3 to here took less than one tick), so frames are locked to the timer's beat;
    • multiplayer: until a packet from every active player has arrived, but never longer than 5 ticks. A player whose packets are missing for 4 frames in a row is no longer waited for until a packet from them arrives again (chapter 8). Then the packets are applied: hits the other players scored on you (shields lost, flash, cloak lost, maybe death) and whether each of them was killed or left the fight. So in multiplayer you take damage at the end of the frame, after drawing.
timer ticks (18.2 per second, 55 ms apart) singleplayer waiting for the next tick multi-player one frame per retrace (~70/s) when all players keep up; a missing player can hold a frame up to 5 ticks
Pacing. Red: single-player frames, each lasting at least one timer tick. Blue: multiplayer frames, limited by the retrace and by the slowest player.

How time is kept

NetWars has two clocks and uses both.

Almost nothing in the game is measured in seconds. Every speed, rate and timer is "per frame": a laser shot moves the same distance each frame and lives 24 frames; a new alien may appear every 64th frame; a collision makes the ship tumble for 48 frames. The time a frame takes therefore decides how fast the game runs:

ModeFrame rateWhy
Single playerat most 18.2 per second Oeach frame waits for at least one timer tick (step 9)
Multiplayerup to about 70 per second, set by the slowest playerframes wait only for the retrace and for the other players' packets; our recorded sessions in the DOSBox-X emulator ran at about 70 packets per second per player O; on a 1993 PC drawing filled polygons it was probably lower H

So on a fast enough computer a multiplayer game runs almost four times as fast as single player: the same per-frame speeds, about four times as many frames per second. On a slow computer (one that needs more than a tick to draw a frame) single player slows down as well; the game does not correct for that.

Per-frame ruleFramesSeconds at 18.2 fpsSeconds at 70 fps
a new alien may appearevery 643.5—
a new satellite may appearevery 1287.01.8
a laser shot lives241.30.34
collision tumble482.60.69
death text before "Press ENTER"64*3.50.9

* In the normal case. In multiplayer a hit reported by a player who then stops sending is applied again every frame and keeps restarting this count (chapter 8).

One screen measures real time with the tick counter instead: the instructions and the high-score table alternate every 200 ticks (about 11 seconds) whatever the frame rate.

Quirk

The level introduction screen also rotates the camera a little every frame, and nothing resets it before the flight. Because that screen runs at the retrace rate (about 70 frames per second), a single-player level starts with the view tilted, anywhere up to upside down, depending on how long you looked at the introduction and on the machine's speed (seen in our test runs, runtime #35; chapter 4).

For a rebuild

Separate the simulation step from the drawing. A modern screen refreshes 60 to 240 times a second, and a browser cannot stop and wait in a loop the way the original does. Run the simulation in fixed steps with all the original per-frame numbers, and draw as often as the screen allows, drawing each object part-way between its last two simulated positions for smooth motion (interpolation).

Choose the step rate on purpose. 18.2 steps per second reproduces single player exactly. The original multiplayer ran at whatever the machines managed (about 70 in our emulator runs); pick one fixed rate for all players in a session, otherwise faster machines would see a faster game. If you change the rate, scale every per-frame speed, rate and timer with it.

Keep the order of the frame. Who moves before whom decides, for example, whether a shot fired this frame can hit something this frame. Use the order in step 7.