MultiGames SDK Developer Guide
MultiGames client library for peer-to-peer multiplayer (2–4 players) and single-player HTML5 games.
1. 30-Second Quickstart
The SDK automatically adapts whether running inside the parent MultiGames iframe shell, connecting to remote peers via WebRTC, or running standalone during local development.
import { createMultiGamesSDK } from '@multigames/sdk';
const sdk = createMultiGamesSDK();
// 1. Initialize session (inherits room & player from URL or platform parent)
const ctx = await sdk.init({
mode: 'MULTIPLAYER',
roomCode: '104200',
});
console.log(`Joined room ${ctx.roomCode}. Role: ${ctx.isHost ? 'HOST' : 'PEER'}`);
// 2. Stream high-frequency 30Hz positions over UDP-style unreliable channel
sdk.onPacket((packet, senderId) => {
updateRemotePlayerPosition(senderId, packet.x, packet.y);
});
// 3. Listen for discrete game events (round start, scores) over reliable TCP-style channel
sdk.onEvent('COIN_COLLECTED', ({ coinId, points }, senderId) => {
spawnCoinEffect(coinId);
incrementScore(senderId, points);
});
2. Core Mental Model (Host Authoritative Simulation)
MultiGames uses an Authoritative Host Star Topology. The first player to create the room is the Host, and players 2–4 are Peers.
ctx.mode === 'SINGLEPLAYER', the SDK bypasses all WebRTC and network routines. sendEvent automatically loops back locally to your own handlers, and sendPacket is an ultra-fast no-op. You write your game once and it runs in both solo and multiplayer modes seamlessly!
3. Installation
Install via package manager for modern bundled workflows (Vite, Webpack, esbuild):
npm install @multigames/sdk
# or
pnpm add @multigames/sdk
Or import directly via CDN in vanilla HTML5 canvas scripts without any build step. Point at the explicit bundle file so the ESM and UMD variants are unambiguous:
<script type="module">
import { createMultiGamesSDK } from 'https://unpkg.com/@multigames/sdk/dist/index.js';
const sdk = createMultiGamesSDK();
</script>
<script src="https://cdn.jsdelivr.net/npm/@multigames/sdk/dist/index.umd.js"></script>
<script>
const sdk = window.MultiGamesSDK.createMultiGamesSDK();
</script>
4. Game Engine Integration Guides
Multiplayer in HTML5 follows a standard client-server pattern using our symmetric SDK:
Peers stream lightweight input vectors (dx, dy) via sendPacket, and the
Host simulates physics at 30 Hz and broadcasts authoritative entity positions via sendPacket.
Discrete milestones (scoring, deaths, round transitions) use reliable sendEvent.
import { createMultiGamesSDK } from '@multigames/sdk';
const canvas = document.getElementById('gameCanvas');
const ctx2d = canvas.getContext('2d');
// 1. Initialize SDK
const sdk = createMultiGamesSDK();
const session = await sdk.init({ mode: 'MULTIPLAYER' });
// 2. Game State & Input Tracking
const keys = new Set();
const peerInputs = {};
const worldState = {
players: {}, // { [id]: { x, y, score, name } }
coin: { x: 300, y: 200 }
};
window.addEventListener('keydown', (e) => keys.add(e.key.toLowerCase()));
window.addEventListener('keyup', (e) => keys.delete(e.key.toLowerCase()));
// 3. Wire Network Packet Dispatch
sdk.onPacket((packet, senderId) => {
if (session.isHost && packet.type === 'INPUT') {
peerInputs[senderId] = { dx: packet.dx, dy: packet.dy };
} else if (!session.isHost && packet.type === 'STATE') {
worldState.players = packet.players;
worldState.coin = packet.coin;
}
});
sdk.onEvent('SCORE', ({ playerId, points }) => {
if (worldState.players[playerId]) {
worldState.players[playerId].score += points;
}
});
// 4. Fixed-Rate Physics Loop (30 Hz)
setInterval(() => {
const dx = (keys.has('d') ? 1 : 0) - (keys.has('a') ? 1 : 0);
const dy = (keys.has('s') ? 1 : 0) - (keys.has('w') ? 1 : 0);
if (session.isHost) {
// Host simulates local player + all remote peer inputs
applyMovement(session.localPlayer.id, dx, dy);
for (const [id, input] of Object.entries(peerInputs)) {
applyMovement(id, input.dx, input.dy);
}
// Authoritative state broadcast to all peers
sdk.sendPacket({ type: 'STATE', players: worldState.players, coin: worldState.coin });
} else {
// Peers stream uncompressed input vector to Host
sdk.sendPacket({ type: 'INPUT', dx, dy });
}
}, 33);
// 5. Render Loop (60 FPS)
function render() {
ctx2d.clearRect(0, 0, canvas.width, canvas.height);
// Draw coin
ctx2d.fillStyle = '#f2cc60';
ctx2d.fillRect(worldState.coin.x - 10, worldState.coin.y - 10, 20, 20);
// Draw all players
for (const p of Object.values(worldState.players)) {
ctx2d.fillStyle = p.id === session.localPlayer.id ? '#58a6ff' : '#3fb950';
ctx2d.beginPath();
ctx2d.arc(p.x, p.y, 16, 0, Math.PI * 2);
ctx2d.fill();
}
requestAnimationFrame(render);
}
requestAnimationFrame(render);
import Phaser from 'phaser';
import { createMultiGamesSDK } from '@multigames/sdk';
export class GameScene extends Phaser.Scene {
async create() {
this.sdk = createMultiGamesSDK();
this.session = await this.sdk.init();
this.cursors = this.input.keyboard.createCursorKeys();
this.peerSprites = new Map();
this.peerInputs = {};
// Create local player sprite
this.player = this.add.circle(200, 200, 18, 0x58a6ff);
this.physics.add.existing(this.player);
// Listen for incoming packets
this.sdk.onPacket((packet, senderId) => {
if (this.session.isHost && packet.type === 'INPUT') {
this.peerInputs[senderId] = packet;
} else if (!this.session.isHost && packet.type === 'STATE') {
this.updatePeerSprites(packet.players);
}
});
// Host runs fixed 30 Hz authoritative tick
if (this.session.isHost) {
this.time.addEvent({
delay: 33,
loop: true,
callback: () => {
const snapshot = {};
this.peerSprites.forEach((sprite, id) => {
snapshot[id] = { x: sprite.x, y: sprite.y };
});
snapshot[this.session.localPlayer.id] = { x: this.player.x, y: this.player.y };
this.sdk.sendPacket({ type: 'STATE', players: snapshot });
}
});
}
// Cleanup on scene shutdown
this.events.on('shutdown', () => this.sdk.disconnect());
}
update() {
const dx = (this.cursors.right.isDown ? 1 : 0) - (this.cursors.left.isDown ? 1 : 0);
const dy = (this.cursors.down.isDown ? 1 : 0) - (this.cursors.up.isDown ? 1 : 0);
if (!this.session.isHost) {
this.sdk.sendPacket({ type: 'INPUT', dx, dy });
} else {
this.player.body.setVelocity(dx * 200, dy * 200);
}
}
updatePeerSprites(players) {
for (const [id, pos] of Object.entries(players)) {
if (id === this.session.localPlayer.id) continue;
let sprite = this.peerSprites.get(id);
if (!sprite) {
sprite = this.add.circle(pos.x, pos.y, 18, 0x3fb950);
this.peerSprites.set(id, sprite);
}
// Smooth interpolation toward authoritative coords
sprite.x = Phaser.Math.Linear(sprite.x, pos.x, 0.3);
sprite.y = Phaser.Math.Linear(sprite.y, pos.y, 0.3);
}
}
}
import * as THREE from 'three';
import { createMultiGamesSDK } from '@multigames/sdk';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// 1. Initialize SDK
const sdk = createMultiGamesSDK();
const session = await sdk.init();
// 2. Create local character mesh & peer pool
const geometry = new THREE.BoxGeometry(1, 1, 1);
const myMesh = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({ color: 0x58a6ff }));
scene.add(myMesh);
const peerMeshes = new Map();
// 3. Synchronize 3D Transforms over Unreliable Packets
sdk.onPacket((packet, senderId) => {
let mesh = peerMeshes.get(senderId);
if (!mesh) {
mesh = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({ color: 0x3fb950 }));
scene.add(mesh);
peerMeshes.set(senderId, mesh);
}
mesh.position.set(packet.x, packet.y, packet.z);
mesh.rotation.y = packet.rotY;
});
// 4. Remove meshes when peers disconnect
sdk.onPlayerLeft(({ playerId }) => {
const mesh = peerMeshes.get(playerId);
if (mesh) {
scene.remove(mesh);
peerMeshes.delete(playerId);
}
});
// 5. Animation & Broadcast Loop
function animate() {
myMesh.rotation.y += 0.02;
// Broadcast transform at display refresh rate
sdk.sendPacket({
x: myMesh.position.x,
y: myMesh.position.y,
z: myMesh.position.z,
rotY: myMesh.rotation.y,
});
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
animate();
5. Platform Services (Ads & Scores)
The SDK bridges directly to the host MultiGames platform over secure iframe messaging. Calls include a 15-second default safety timeout with graceful fallback, so games never freeze if the parent shell does not reply.
// sdk is an initialized MultiGames SDK instance
// 1. Rewarded Ad: User-initiated, grants in-game bonus upon completion
const { watched } = await sdk.showAd('REWARDED');
if (watched) {
grantExtraLives(3);
}
// 2. Interstitial Ad: Natural level-transition or game-over full-screen ad
await sdk.showAd('INTERSTITIAL');
// 3. Leaderboard Score Submission
await sdk.submitScore(12500);
showAd automatically simulates a completed ad view and submitScore alerts via native modal, letting you build and test freely without a running platform container.
6. Local Standalone Testing
When running standalone without a platform iframe, the SDK automatically connects to the hosted cloud signaling service via WebSocket. Pass custom options or query parameters to simulate rooms and players instantly:
| Query Param | Accepted Values | Default | Behavior |
|---|---|---|---|
?room= |
Numeric or alphanumeric (e.g. 104200, arena-1) |
Auto-generated | Room code (3–32 chars, letters, digits, _, -) shared across tabs. |
?name= |
String (e.g. Fox_Racer) |
Random guest nickname | Display name for the local player. |
?host= |
true | false | 1 | 0 |
First tab in room becomes Host | Forces Host or Peer role for deterministic testing. |
7. TypeScript Contracts & Enums
export type NetworkMode = 'SINGLEPLAYER' | 'MULTIPLAYER';
export type AdType = 'INTERSTITIAL' | 'REWARDED';
export type Player = {
id: string;
name: string;
isHost: boolean;
isGuest: boolean;
isReady?: boolean;
avatarUrl?: string;
};
export type LobbyState = {
roomCode: string;
status: 'WAITING' | 'STARTING' | 'IN_PROGRESS' | 'CLOSED';
maxPlayers: number;
hostId: string;
players: Player[];
};
export type SessionContext = {
mode: 'SINGLEPLAYER' | 'MULTIPLAYER';
roomCode?: string;
maxPlayers: number;
isHost: boolean;
localPlayer: Player;
players: Player[];
lobby?: LobbyState;
};
export type InitOptions = {
mode?: NetworkMode;
roomCode?: string;
maxPlayers?: number;
player?: {
id?: string;
name?: string;
avatarUrl?: string;
isHost?: boolean;
isGuest?: boolean;
};
};
// Full API surface (all methods) is declared by the exported MultiGamesSDK type.
// init, disconnect, getContext, sendEvent, onEvent, sendPacket, onPacket,
// onLobbyUpdated, onPlayerJoined, onPlayerLeft, onDisconnected, showAd,
// submitScore and onAudioMuteToggle are all typed in dist/index.d.ts.