Skip to content

Multiplayer and servers ​

One process runs the world on a server; each player's page holds a seat and gets only what that seat may know (server-authoritative). Players send commands; the server sends snapshots. For a step-by-step recipe, see An online game.

Quick start ​

ts
// server.ts, run with Node 22
import { startServer } from '@v12-engine/engine/server'
const server = await startServer({ rules, map, onStart, ai: [2], port: 8787 })
ts
// the page
launch({ target: '#game', game, session: () => connect(await openSocket('ws://localhost:8787'), { rules: game.rules }) })

Each player of the map with a start gets a seat, the computer plays seat 2, and the game starts once the seats are taken. The client draws a RemoteSession exactly as it draws a game in the page.

Common tasks ​

Log players in ​

ts
startServer({
	rules,
	map,
	seat: async ({ ticket }) => {
		const user = await logins.check(ticket)
		return user ? { player: user.seat, name: user.name, id: user.id } : { refuse: 'log in first' }
	}
})

seat gets a SeatRequest (address, name, ticket, free seats, phase). A player coming back with the same id gets their seat back, from another page or after a drop within abandonAfter.

Show a lobby ​

ts
import { createScenes, onlineScene } from '@v12-engine/client/app'
const scenes = createScenes([onlineScene({ rules: game.rules, url: 'wss://example.com/game' })])

Players take seats, rename, chat, vote to kick, change settings and say ready. Draw your own with createLobby() (seats, you, said, sit, rename, setReady, set, start, join, reconnect) and onlineScene({ lobby: { component } }), or wrap LobbyScreen.

Offer settings for each seat ​

Give the rules' server hooks a seatSettings record (ServerHooks.seatSettings, each a LobbySetting: a colour, a hero). Each seat has them at their defaults, set by who sits there (or anyone for a computer or empty seat). Races, and a difficulty and personality for computer seats (where the game has Rules.ai), are offered by themselves; mapMode also offers a team and a unique colour per seat (seatLooksOf). The computer player of a seat is told its own (GameMode.ai(seat, seats, settings)).

Let people watch ​

ts
startServer({ rules, map, watch: { key: 'secret' }, watchDelay: 60 })

watch: true lets anyone in once the seats are taken, { key } who brings the key, or a function per request (WatchRequest). Watchers see the whole map, so watchDelay holds what they see back (delayed(transport, seconds)). To share a game played in a page, shareGame goes through a relay (npm run server -- --relay); a campaign does it with CampaignDef.watch.

Many games on one port ​

ts
import { GameRooms, mapMode } from '@v12-engine/engine/server'
import { rules, onStart } from './src/rules'

const rooms = await GameRooms.start({
	port: 8787,
	rooms: { arena: { mode: mapMode(rules, arenaMap, { onStart }) }, duel: { mode: mapMode(rules, duelMap, { onStart }) } }
})

Each room is at its own path (ws://host:8787/arena). They share one thread: watch vg_tick_seconds_total against vg_ticks_total (a tick has 33 ms at 30 a second), and add processes past that.

Let players make games, find games and get matched ​

Give GameRooms kinds (each a name and the room it makes). Players then POST /games with { kind, settings }, browse GET /games (GameListing), or queue at ws://host:8787/queue with { type: 'queue', kind, name } and get { type: 'matched', room, ticket }. The client's Find a game scene (findGameScene) does all three. A random map per room: room: (settings) => ({ mode: generatedMode(rules, rules.generator!, { width: 128, depth: 128, players: 2, symmetry: 'half', onStart }) }).

Keep ratings ​

ts
GameRooms.start({ port: 8787, rooms, kinds, ratings: createRatings({ file: 'ratings.json' }) })

Elo per mode. Browsers join with a key of their own (join's who), stored only as a hash (ratedId); with logins, the seat hook's id. GET /ratings?mode=melee&n=10&player=<rated id> gives the top and the player's place.

Share control of units with an ally ​

ts
world.sides.share(player, withPlayer, { control: true, vision: true })

Players do it from the HUD's Allies panel (share command). world.mayCommand(player, entity) (or your settings.mayCommand) decides what each player may command. A map force with sharedControl starts shared.

Show enemies more on unit plates ​

ts
settings: {
	hud: {
		shareBuffTimes: (_world, entity) => entity.has(heroState), // or true, 'allies', false (default)
		shareAbilities: 'icons', // 'none' (default), 'icons', 'cooldowns'
		shareXp: true
	}
}

For your own data, use a component with the audience you mean and read it on the plate with hudData(entity, fury).

Hide buildings from pathfinding in the dark ​

ts
export const rules: Rules = { ...game, paths: 'seen' }

Otherwise where a unit turns in the dark gives an unseen building away. Costs a navigation per side (about 11 MB on a 512-cell map).

Handle cheaters ​

ts
startServer({ rules, map, onCheat: (report) => (report.recent > 5 ? 'kick' : 'warn'), cheating: { kickAfter: 20, seconds: 10 } })

CheatReport has the seat, address, kind, reason, and the recent and total counts. server.kick(player, reason) lets a player go from code.

Run it in production ​

ts
process.once('SIGTERM', () => void server.close({ drain: 30 })) // no new games; the running one gets 30 s to end
nginx
location /game/ {
	proxy_pass http://127.0.0.1:8787/;
	proxy_http_version 1.1;
	proxy_set_header Upgrade $http_upgrade;
	proxy_set_header Connection "upgrade";
	proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
	proxy_read_timeout 120s; # longer than the server's idleTimeout (60 s)
}

Caddy: reverse_proxy 127.0.0.1:8787. The page joins wss://example.com/game/arena. Image: docker build -f apps/example/Dockerfile -t vg-server ., then docker run -p 8787:8787 vg-server --mode arena --ai 2; give the orchestrator longer than the drain (docker stop -t 40, terminationGracePeriodSeconds).

Reference ​

How the pieces fit ​

   simulation (World)                                player's screen (client)
 ┌──────────────────────────┐   snapshots   ┌──────────────────────────────┐
 │ World                    │ ────────────► │ GameState (what I know)      │
 │  orders, combat, fog ... │               │  renderer, minimap, HUD      │
 │                          │ ◄──────────── │ PlayerController             │
 └──────────────────────────┘   commands    └──────────────────────────────┘
              ▲                                        ▲
              └────────────── GameSession ─────────────┘
PieceWhat it is
GameSessionThe only thing a client holds: snapshots out, commands in
LocalSessionRuns the world in the page, filtering by what the team sees
SessionHostRuns a world for players over transports, a seat each, sending JSON deltas
RemoteSessionThe player's side (from connect)
loopbackBoth ends of a transport in the page, with latency, jitter and loss, for tests
startServerA game server (@v12-engine/engine/server); underneath, GameServer.start with a GameMode (mapMode)

Lockstep (every client runs the whole game) is not used: it allows map hacks and needs identical floating point everywhere.

startServer options ​

OptionWhat it does
map, seatsA seat per map player with a start, or { player, name, team? } listed
onStart(world, { map, settings })Runs on each new world
makeWorld(settings)Makes each world in code, in place of map
ai, computerSeats the computer plays; its options by seat, a brain (computer: myBrain), or null for none. Per seat: GameMode.brain
seatLogins (above); a function that throws refuses and is logged
watch, watchDelay, adminKey, abandonAfterWatchers, admin, how long a dropped seat is held
onCheat, cheating, rate, messageRate, lobbyRateCheating and rate limits
logA Logger (new Logger(), to(sink)) or a function of lines; else the console
http{ health, metrics, metricsKey, games, ratings }: move or turn off addresses
idleTimeout, joinWithin, maxConnections60 s, 10 s, 1024
navigationWorkerfalse builds navigation on the server's thread

What a player gets to know ​

InformationOwn and alliedEveryone else
Position, type, healthAlwaysOnly while in sight
Orders, queue, rally point, carried goldYesNever
Gold, supply, researchOwn player onlyNever
Buildings out of sightAs last seen, until someone looks again
A name the map or rules gave itYesWhile known of
Deaths, attacks, projectilesYesOnly in sight
Terrain and game dataEveryone, from the start
Health, mana, level, buffs and stacksYesWhile in sight
Abilities and cooldowns, a hero's xpYesWhere the rules share them (hud)
Seconds left of buffsWhere the rules share themWhere the rules share them (hud)
A game's own componentAs its replicate saysAs its replicate says, while in sight

Pings are commands (pingCommand), limited by RuleSettings.talk.pings and the beforeTalk hook, sent to allies and observers or everyone (to: 'all'). Floating numbers ride on events already sent. See Indicators.

What can still be worked out by a client written to look: paths round unseen buildings (unless paths: 'seen'), where you cannot build (cannotBuildThere on an explored cell an unseen building holds), and how many units everyone made (ids are sequential).

The lobby protocol ​

The server sends lobby (seats with team and ready, the game, settings). Players send sit, name, ready, setting, start, lobbyChat, kick (a vote; ServerSeat.kick), seatSetting (lobby.setSeat). Observers' chat goes to observers only (ChatAudience), marked [Observers]. The name a player goes by is kept in the settings (playerName).

Connection, versions, pauses ​

  • Reconnect: the page rejoins with its seat token and back: true (RemoteSession.resume(transport)); the client retries for half a minute (RETRY_WAITS, the HUD's connection part). A token that leads nowhere is refused (SessionRefused). session.onDisconnect for your own handling.
  • Versions: PROTOCOL_VERSION is checked both ways on join; game data by Registry.dataHash. Content packs are part of the game's id and hash (melee+gnomes): see Mods.
  • Pause and surrender: pause holds the game for everyone (paused) until a seated player sends { type: 'resume' } or time is up; surrender is a defeat. On the page: client.endings, the HUD's paused part. After a game, joining again with the seat token returns the server to its lobby.
  • Talk while paused: commands with outsideTick (chat, pings; defineCommand(type, fields, execute, { outsideTick: true })) run between ticks.
  • Rules that throw end that game only (GameResult.failed, session.failure), never the process. See Errors.

Cheating and limits ​

A command a real client never sends is refused (commandRejected), counted per seat, logged, and passed to onCheat (ignore, warn, kick, end; default warn, kick after cheating.kickAfter in cheating.seconds, 20 in 10). Over-rate commands are dropped and answered tooManyCommands. Keys are compared in constant time.

WhereOptionDefaultWhat it bounds
createWorldtickRate30Steps a second; saves at another rate are refused
worldcommandLimit100Commands a player per tick
SessionHostOptionskeptFrames64Frames kept per player for deltas
SessionHostOptionskeptEvents600Ticks of unacknowledged events; dropSilentAfter lets a silent player go
SessionHostOptionsgroundPart262144Characters of ground per message
GameServerOptionsrate30/s, 60 at onceCommands
GameServerOptionsmessageRate100/s, 200 at onceOther messages
GameServerOptionslobbyRate4/s, 20 at onceLobby messages
ConnectOptions.limits (PlayerLimits)keptSnapshots64Snapshots waiting for a screen that does not ask
ConnectOptions.limitskeptScreenEvents2000Events carried by folded snapshots
ConnectOptions.limitsmaxJitter0.2 sInterpolation room for a late message
ConnectOptions.limitspingEvery2000 msBetween two latency pings
new LocalSession(…, options)mostEffects1024Effects kept for their stop

A page in the background keeps three seconds of snapshots at most (session.waiting). Positions are quantised to 256ths of a unit and facings to 256ths of a turn (a protocol constant).

Production details ​

  • /health: 200 while taking games, 503 while stopping.
  • /metrics: Prometheus text (or ?json, or server.metrics()): vg_games_running, vg_games_played_total, vg_players, vg_watching, vg_connections, vg_ticks_total, vg_tick_seconds_total, vg_last_tick_seconds, vg_sends_total, vg_send_seconds_total, vg_bytes_sent, vg_memory_bytes, vg_protocol_version.
  • A map the game ships is welcomed by name and ground hash; a player without it is sent the ground in 256 KB parts.
  • Navigation is built in a worker thread (server/navigation-worker.js beside server/navigation.js in the engine's dist) and cached by ground hash. A bundled server builds the worker file next to it.
  • Rooms made on demand close after emptyFor (60 s) empty; maxMade (16) at once; three a minute per address.
  • Not there yet: a list of servers, and saved games over the network.

Rules the code keeps ​

  1. The client never imports the world (npm run lint checks it).
  2. Everything that changes the game is a command, as plain data.
  3. The session stamps the player; the simulation checks ownership.
  4. Commands only name what the player can know.
  5. The simulation decides; client checks are only for feedback.
  6. Snapshots are plain data.
  7. No Math.random or clock in the simulation.
  8. Debug tools go through client.debug, which exists only when the simulation runs in the page.

Computer players run on the server like any seat, under their own fog; a team's computers share a board (core.ai.teams) that no player is sent. See Computer players.