13. Building it again: a browser version
Everything from the previous chapters, put together for one concrete goal: NetWars in a web browser, at any resolution, where friends join a game by opening a link, with no host and no "start match", just as in 1993. This chapter is a plan, not code: what to keep, what to change, how to organise the program, and how the network works without a game server.
The contract: what must stay the same
"Plays like the original" means a fixed list of things. Keep these, and the game will feel like NetWars; change them, and it becomes a different game:
- All per-frame numbers (chapters 4 to 7): turn rates and ramps, the velocity controller, the throttle range, shot speed and lifetime, alien speeds and turn rates, spawn and pick-up periods, timers.
- The simulation step rate those numbers were made for (chapter 2): 18.2 steps per second in single player; one shared fixed rate in multiplayer (about 70 matches the original).
- The nearness tests and hit boxes as cube tests on the largest coordinate difference and boxes in the shot's frame (chapters 3 and 6), with the "Exact rules".
- The rules: alien behaviours and thresholds, pods, satellites and their cycle, levels, scoring, shields, limits of the object tables (chapters 5 and 7).
- The models, colours and view: the 22 models in assets/models/, flat faces in the 16 EGA colours, a 64° × 49° view (chapter 9), the instruments (chapter 1).
- The multiplayer model: no host, a slot per player, each machine the authority for its own ship and shots, the shooter deciding hits, collisions judged locally (chapter 8).
Free to change: the resolution, smooth drawing between steps, a depth buffer, sound quality, the network transport, and any bug you decide to fix (chapter 12), as long as you decide it on purpose.
The parts of the program
The simulation core
- One function advances the world by exactly one step: step(state, inputs, messages) → state, outgoing message, events. It runs the frame order of chapter 2 (player, shots, aliens or other players, satellites), including the "seen from you" values of chapter 5 that the rules need.
- Run it on a fixed clock: accumulate real time and call step as many times as the elapsed time requires, independent of the screen's refresh. Single player uses the exact timer rate, 1,193,182 ÷ 65,536 = 18.2065 steps per second (54.925 ms); multiplayer a fixed rate that every browser shares (about 70). Cap the catch-up at a few steps per screen frame, so that coming back from a long pause does not run thousands of steps at once.
- Browsers stop drawing hidden tabs and slow their timers to about once a second. Decide what a hidden tab means: pause in single player; in multiplayer either leave the flight or keep stepping and sending in a Worker, otherwise the others drop you.
- Use 64-bit floating-point numbers, but write small helpers that reproduce the original where it
matters: the distance exponent (two loops on whole units), dot products of whole-unit vectors
with axes, the box tests with inclusive limits (the "Exact rules" boxes of chapters 3 to 9). The
repository's check (tools/doccheck/) compares such helpers with the original
code run in an emulator. It needs the private repository with the unpacked original program and
expects the helpers in Python (impl.py, interface in
tools/doccheck/API.md; run
.venv/bin/python -I tools/doccheck/compare.py impl.py). For JavaScript, port the helpers to that file once, or use its oracle to export test cases as JSON for your own tests. - Keep the data in the original's units (world units, steps of 1/2048 turn, speeds ÷ 4) so that every number in this document can be copied as it is.
The renderer
- Draw at any resolution inside a 4:3 area (letterbox the rest), with the original's view: vertical field of view 49° and aspect 1.371 passed to the perspective function, although the drawing area is 4:3 (chapter 9 explains why). Scale line widths, discs, the font and the instruments with the resolution, x and y separately so their shapes stay as on the 4:3 monitor.
- Draw each object at a position interpolated between the last two simulation steps, so the picture is smooth at 60–240 frames per second while the game still runs at 18.2 or 70 steps. Interpolate the orientation too (blend the axes and make them perpendicular again, or use quaternions).
- Flat faces, the EGA palette, a depth buffer (or the original painter's sort for authenticity), back faces culled with clockwise front faces (camera up = −c, chapter 3).
Audio
One square-wave oscillator followed by a gain node (a raw square wave is harsh), its frequency
changed once per timer tick from the effect tables (chapter 10), scheduled on the audio clock with
setValueAtTime rather than with timers. Keep the rule that a new effect replaces the
running one. Browsers start audio suspended: create or resume the audio context on the first click or
key press.
Input
- Keep a "held" table from
keydown/keyupevents and latch presses until the core reads them, as the original key table does (chapter 11). - Some combinations cannot be blocked by a page at all: Ctrl+W, Ctrl+T, Ctrl+N, system shortcuts
such as Ctrl+arrows on macOS (which collide with "brake while steering"), and Esc while the pointer
is locked. Default the throttle to keys without such conflicts, call
preventDefaultfor the rest (F1, Space, arrows, Alt), readevent.codeso keyboard layouts do not matter, and offer remapping. Caps Lock gives unreliable key events in some browsers; offer another missile/cloak key. - Clear the "held" table when the window loses focus (
blur,visibilitychange), or a key released elsewhere stays held. - Mouse steering is a joystick: use Pointer Lock (it needs a click to start) and accumulate movement into a virtual pointer inside the flight box (chapter 4). The browser's Esc always unlocks the pointer; treat that as "pause / open the menu", not as the game's Esc.
Multiplayer without a game server
The original's model (chapter 8) fits the browser almost directly. The only new part is that browsers on the internet cannot find each other by broadcasting; something must introduce them.
The invitation link and the signalling service
- A room is a universe; it replaces the lobby's Universe menu. The invitation link carries
a room name, for example
https://example.org/netwars#room=k7Qx2mZp9aLw. Make it random and long: anyone who has the link can join. - A small signalling service keeps, per room, the list of browsers currently present and relays the WebRTC connection set-up messages (offers, answers, network candidates) between them. It runs no game logic and stores nothing of the game. It can be a tiny WebSocket server or a hosted real-time service.
- When a browser opens the link it joins the room on the service, gets a stable peer id from it, learns who is there, and opens a direct WebRTC connection to each of them. The newcomer sends the offers; members only answer, so two browsers never offer to each other at once. The service also tells members when someone's connection to it closes. Connections already open keep working if the service goes down; only newcomers are stuck.
- Mesh size: players connect to each other (3 connections each) and to every spectator; spectators send nothing, so they need connections only to the 4 players. Lobby visitors can get the slot list from the service and stay out of the mesh. One state message per step is about 130 bytes plus 60–80 bytes of transport overhead; at 70 steps per second to 7 peers that is roughly 0.5–1 Mbit/s of upload.
- Browsers behind home routers need a STUN server (public ones exist) to learn their public address; without it most connections fail. When even that fails (strict company, school or mobile networks), a TURN relay forwards the encrypted traffic. It is a server, but a dumb pipe: it does not know or decide anything about the game. TURN costs bandwidth and needs credentials: hand out short-lived ones from the service, never a fixed secret in the page.
Because the game state lives only in the players' browsers, the person who sent the invitation can leave and the others play on. Anyone can join later with the same link, as long as the signalling service is running, because it is the service, not any player, that introduces newcomers.
Messages
| Message | When | Channel | Content |
|---|---|---|---|
| state | every simulation step, to every peer | unreliable, unordered
({ordered:false, maxRetransmits:0}), binary | slot, step number, name, position, velocity, axes, status, score, satellite (kind, position), shot flags (as in the original packet, chapter 8) |
| hit | when your shot hits someone | reliable (a second channel with default options) | event id (sender peer id, counter), victim slot and victim peer id, powered |
| satellite event | when you collect or shoot someone's satellite | reliable | event id, owner slot and owner peer id, collected or shot |
| slot claim / release | joining and leaving a slot | reliable | slot, peer id |
| presence | lobby | the signalling service (recommended) | who holds which slot |
- Each receiver keeps the newest state per player (drop messages with an older step number) and applies each event id exactly once. That one change removes the original's worst bug, the hit that is applied again every frame (chapter 8). The victim ignores events addressed to another peer id, so a late hit cannot strike a newcomer who just took the same slot.
- The step number is the sender's own counter, used only to drop old messages. There is no shared global step, no lockstep and no need for identical random numbers across browsers, because each browser decides only for its own objects (chapter 8).
- Skip a state message when the channel's
bufferedAmountis high, as the original sends only when the previous send has finished. - Put a protocol version and the step rate in a hello message and refuse mismatches.
- The state message is a full snapshot, so a newcomer or a spectator sees every ship within one step; only shots already in flight are missing.
Rules to decide
- Slots: before showing slots as Free, wait until the connections to every member listed by the service are open (or a few seconds have passed). Claim a slot with a message; if two browsers claim the same slot, the lower peer id keeps it and the other returns to the lobby. Simpler: let the signalling service hand out slots.
- Partial mesh: if one member cannot reach another, treat a member unreachable after a few seconds as absent and show it in the lobby.
- Step rate: all players use the same fixed rate. Do not stall for slow peers as the original did; show other ships interpolated from their latest messages, and drop a player that has sent nothing for about a second (the original's 4-frame rule, half a second to a second in practice, is too strict for the internet).
- Hits are tested against what is drawn: the original tests against the same position it draws. Test against the same interpolated position you draw, so "the shooter decides" still means "what the shooter saw".
- Spectators are members with no slot that receive and never send (chapter 8).
- Reconnect: on a failed connection try
restartIce(). A page reload loses the slot and score, as a crash did in the original; keep them insessionStorageand reclaim if you want to soften that. - Who decides hits: the original's "the shooter decides" is simple and keeps aiming honest on the shooter's screen, but with internet delay a victim may be hit after reaching cover on its own screen. Keeping it is the faithful choice; anything else is a design change.
- Cheating: like the original, every browser trusts the others. For games among friends this is fine; if it matters, check that reported hits are plausible (distance, shot timing).
Bugs: keep or fix?
Chapter 12 lists the original's bugs and oddities. A suggested default for a rebuild:
| Behaviour | Suggestion | Why |
|---|---|---|
| repeated hit reports, two players in one slot, two hits in one frame counting once, stale satellite events | fix | broken play, no one would miss them |
| camera rolled by the level introduction | fix | an accident with no gameplay meaning |
| no near clipping, painter's sort errors | fix or keep | visual only; keeping is authentic |
| laser tunnelling and blind spots, cube-shaped nearness | keep | they shape how combat feels |
| collision push along a fixed world axis | keep or soften | odd, but part of the original's feel |
| missile lock as a square beam (off-screen locks) | keep | a gameplay rule players learn |
A building order
- The core helpers (distance exponent, rotations, dot products) with tests against the original through tools/doccheck/.
- Flying alone: ship control, stars, the instruments, one pod drawn with the renderer.
- Single player: aliens one kind at a time, shots and hits, pods, satellites, levels, score.
- Sound, menus and screens.
- Multiplayer through a simple in-browser transport first (
BroadcastChannelbetween two visible windows; a background tab is slowed down and stops sending), with an optional layer that adds 50–150 ms of delay and some loss; then the signalling service and invitation links, then other machines (chrome://webrtc-internalsandabout:webrtcshow what the connections do). - Polishing: interpolation, resolution scaling, key remapping, the bug decisions above.