# How to add multiplayer to an AI-generated game

> A practical architecture guide for adding real-time multiplayer to a game built with Claude Code, Codex, or Cursor—covering server authority, WebSockets vs. WebRTC, and hosting.

Published: 2026-11-20 · Updated: 2026-12-01 · Canonical: https://pita.sh/blog/how-to-add-multiplayer-to-an-ai-generated-game

Adding multiplayer to an AI-generated game works best when you introduce a **single authoritative server** early, keep the message protocol in **one shared file**, and start with **WebSockets** before worrying about UDP or complex client-side prediction.

Coding agents handle multiplayer well when the boundary between client and server is explicit, and struggle when game state is scattered across ad-hoc callbacks.

## 1. Choose the right networking model first

- **Turn-based or slow-paced games (card games, strategy, co-op puzzles):** A simple authoritative Node.js or Go server over WebSockets (or even HTTP + SSE) is plenty. No interpolation or prediction needed.
- **Real-time action games (top-down shooters, racing, arena brawlers):** Run a fixed-tick simulation loop (20–30 Hz) on the server, send player inputs up, and broadcast compact world snapshots down. Interpolate other players' positions smoothly on the client.
- **Peer-to-peer (WebRTC without a game server):** Saves server costs, but requires a signaling server anyway, breaks behind strict NATs without TURN relays, and makes cheating or host-disconnects hard to handle. For most indie projects, a small authoritative server is simpler to build and debug.

## 2. Structure your repo so your coding agent stays in sync

The #1 bug when AI agents write multiplayer code is client/server protocol drift—the client sends `{ dx, dy }` while the server expects `{ x, y }`. Prevent this with a three-folder layout:

```text
shared/
  protocol.ts   # Message types, constants, shared collision/math helpers
client/
  ...           # Rendering, input capture, snapshot interpolation
server/
  ...           # Room/lobby manager + fixed-tick authoritative simulation
```

Prompt your coding agent to define every client→server and server→client message as a discriminated union in `shared/protocol.ts` first, and import that file on both sides.

## 3. Pick a transport and framework

- **WebSockets (`ws`, Colyseus, Socket.IO, Go `gorilla/websocket`):** Easiest to start with, works through firewalls, and handles almost every 2D and casual 3D browser game cleanly.
- **WebRTC DataChannels (unreliable/unordered):** Worth adding if you have twitchy 60fps physics where TCP head-of-line blocking causes noticeable rubber-banding.

## 4. Test with two browser windows locally before deploying

Always verify multiplayer locally first:
1. Run the server locally (`npm run dev:server`) and open two separate browser windows (or an incognito window) side by side.
2. Add a simple synthetic latency toggle (e.g. delaying outbound messages by 80–120 ms in dev) so you can catch jitter and desyncs before real players hit them.

## 5. Hosting the server and database

Once it works locally, you need somewhere to run the server alongside your web client:

- **DIY stack:** Host the static client on Cloudflare Pages or Vercel, run the WebSocket server on Fly.io, Railway, or Render, and add a managed Postgres database (like Neon or Supabase) if you need accounts, progression, or leaderboards. Make sure you configure CORS, TLS (`wss://`), and a way to sleep idle servers so you don't pay for empty rooms.
- **All-in-one game workspace:** On [Pita](/), you declare `[servers.central]` (for lobbies, matchmaking, and persistent state) and optional per-match `[servers.instance]` in `pita.toml` as either a JavaScript ES module (`@pita/sdk/server`) or a WebAssembly (`.wasm`) binary (C, C++, Rust, Odin, Zig). Pita runs them over TLS WebSockets (`wss://`) with **built-in persistent SQLite**, auto-hibernates idle servers at zero CPU with no hourly billing, handles authenticated connect tokens and central↔instance RPC, and lets your coding agent read live server logs, query live SQLite state, and spawn isolated test players directly.

## FAQ

### Should I build single-player first and add multiplayer later?
Build a minimal playable movement loop first, then wire multiplayer before adding lots of content (weapons, enemies, inventory). Retrofitting networking onto a finished single-player codebase usually requires rewriting half the state management.

### How many players can one small multiplayer server handle?
A single lightweight Node.js or Go server running a 20 Hz tick loop can comfortably handle dozens of concurrent players in simple 2D/3D rooms, as long as you send compact snapshots and avoid running heavy 3D rendering on the server.
