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
// server.ts, run with Node 22
import { startServer } from '@v12-engine/engine/server'
const server = await startServer({ rules, map, onStart, ai: [2], port: 8787 })// 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
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
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
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
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
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
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
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
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
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
process.once('SIGTERM', () => void server.close({ drain: 30 })) // no new games; the running one gets 30 s to endlocation /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 ─────────────┘| Piece | What it is |
|---|---|
GameSession | The only thing a client holds: snapshots out, commands in |
LocalSession | Runs the world in the page, filtering by what the team sees |
SessionHost | Runs a world for players over transports, a seat each, sending JSON deltas |
RemoteSession | The player's side (from connect) |
loopback | Both ends of a transport in the page, with latency, jitter and loss, for tests |
startServer | A 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
| Option | What it does |
|---|---|
map, seats | A 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, computer | Seats the computer plays; its options by seat, a brain (computer: myBrain), or null for none. Per seat: GameMode.brain |
seat | Logins (above); a function that throws refuses and is logged |
watch, watchDelay, adminKey, abandonAfter | Watchers, admin, how long a dropped seat is held |
onCheat, cheating, rate, messageRate, lobbyRate | Cheating and rate limits |
log | A 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, maxConnections | 60 s, 10 s, 1024 |
navigationWorker | false builds navigation on the server's thread |
What a player gets to know
| Information | Own and allied | Everyone else |
|---|---|---|
| Position, type, health | Always | Only while in sight |
| Orders, queue, rally point, carried gold | Yes | Never |
| Gold, supply, research | Own player only | Never |
| Buildings out of sight | As last seen, until someone looks again | |
| A name the map or rules gave it | Yes | While known of |
| Deaths, attacks, projectiles | Yes | Only in sight |
| Terrain and game data | Everyone, from the start | |
| Health, mana, level, buffs and stacks | Yes | While in sight |
| Abilities and cooldowns, a hero's xp | Yes | Where the rules share them (hud) |
| Seconds left of buffs | Where the rules share them | Where the rules share them (hud) |
| A game's own component | As its replicate says | As 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'sconnectionpart). A token that leads nowhere is refused (SessionRefused).session.onDisconnectfor your own handling. - Versions:
PROTOCOL_VERSIONis checked both ways on join; game data byRegistry.dataHash. Content packs are part of the game's id and hash (melee+gnomes): see Mods. - Pause and surrender:
pauseholds the game for everyone (paused) until a seated player sends{ type: 'resume' }or time is up;surrenderis a defeat. On the page:client.endings, the HUD'spausedpart. 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.
| Where | Option | Default | What it bounds |
|---|---|---|---|
createWorld | tickRate | 30 | Steps a second; saves at another rate are refused |
world | commandLimit | 100 | Commands a player per tick |
SessionHostOptions | keptFrames | 64 | Frames kept per player for deltas |
SessionHostOptions | keptEvents | 600 | Ticks of unacknowledged events; dropSilentAfter lets a silent player go |
SessionHostOptions | groundPart | 262144 | Characters of ground per message |
GameServerOptions | rate | 30/s, 60 at once | Commands |
GameServerOptions | messageRate | 100/s, 200 at once | Other messages |
GameServerOptions | lobbyRate | 4/s, 20 at once | Lobby messages |
ConnectOptions.limits (PlayerLimits) | keptSnapshots | 64 | Snapshots waiting for a screen that does not ask |
ConnectOptions.limits | keptScreenEvents | 2000 | Events carried by folded snapshots |
ConnectOptions.limits | maxJitter | 0.2 s | Interpolation room for a late message |
ConnectOptions.limits | pingEvery | 2000 ms | Between two latency pings |
new LocalSession(…, options) | mostEffects | 1024 | Effects 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, orserver.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.jsbesideserver/navigation.jsin the engine'sdist) 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
- The client never imports the world (
npm run lintchecks it). - Everything that changes the game is a command, as plain data.
- The session stamps the player; the simulation checks ownership.
- Commands only name what the player can know.
- The simulation decides; client checks are only for feedback.
- Snapshots are plain data.
- No
Math.randomor clock in the simulation. - 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.