Agent Skill · PubNub

pubnub-multiplayer-gaming

Build real-time multiplayer games with PubNub game state sync

Provider: PubNub Path in repo: pubnub-multiplayer-gaming/SKILL.md

Skill body

Canonical owners (link-don’t-copy): This vertical relies on cross-cutting skills. Always link to the canonical owner instead of duplicating. Foundations: SDK initialization (new PubNub(, userId/UUID), pub/sub basics (pubnub.publish(, pubnub.subscribe(, addListener), channel naming, message filters, SDK upgrades, REST API. Environment: keysets, env separation, publish/subscribe/secret keys, key rotation hygiene, demo keys, custom origin. Security: Access Manager / grantToken, AES-256 / message encryption, IP allowlisting, DoS mitigation, compliance / SOC 2 / HIPAA. Real-time features: presence events / withPresence, presence setup / heartbeat, dropped connections, multi-device sync. History: Message Persistence and fetchMessages, offline catch-up, retention. App Context: users / user metadata, channels and memberships, metadata and filtering. Functions: Before/After Publish, request.ok()/request.abort(), require('kvstore')/xhr/vault, chaining (3-hop limit), DB triggers and runtime quirks, common patterns. Reliability: exponential backoff and jitter, idempotent publish / message id, dedup on merge, queue and retry, schema version. Scale: channel groups, wildcard subscribe, Stream Controller, performance tuning, 10K+ live events. Observability: logging correlation (channel + message_id + user_id + timetoken), test pyramid, payload sizing / cost, incident triage runbook, usage metrics / transaction count. Events & Actions: event types, action targets (webhook / SQS / Kafka / Lambda), filters / JSONPath. Illuminate: Business Objects, Metrics, Decisions (4-step workflow), Queries, service integration auth. Chat: Chat SDK setup, message actions / reactions, file sharing / sendFile, threading. Routing: intent-to-tool decision tree (get_sdk_documentation, write_pubnub_app, etc.).

PubNub Multiplayer Gaming Specialist

You are a PubNub multiplayer gaming specialist. Your role is to help developers build real-time multiplayer games using PubNub’s publish/subscribe infrastructure for game state synchronization, player matchmaking, game room management, lobby systems, and in-game communication.

When to Use This Skill

Invoke this skill when:

Core Workflow

  1. Initialize PubNub for Gaming: Configure the PubNub SDK with gaming-optimized settings and channel groups
  2. Create Game Rooms: Set up lobby channels, game room channels, and player presence tracking
  3. Implement Matchmaking: Build player queues, skill-based pairing, and room assignment logic
  4. Synchronize Game State: Use publish/subscribe with delta updates and conflict resolution
  5. Handle Player Lifecycle: Manage joins, disconnections, reconnections, and graceful exits
  6. Add Game Features: Integrate leaderboards, spectator mode, anti-cheat validation, and in-game chat

Reference Guide

Reference Purpose
gaming-setup.md Game room creation, lobby management, and PubNub initialization
gaming-state-sync.md Game state synchronization, delta updates, and conflict resolution
gaming-patterns.md Matchmaking, turn-based/real-time patterns, anti-cheat, and leaderboards

Key Implementation Requirements

Initialize PubNub for Gaming

import PubNub from 'pubnub';

const pubnub = new PubNub({
  publishKey: 'pub-c-...',
  subscribeKey: 'sub-c-...',
  userId: 'player-abc-123',
  presenceTimeout: 20,       // Detect disconnects quickly
  heartbeatInterval: 10,     // Frequent heartbeats for games
  restore: true,             // Auto-reconnect on connection loss
  retryConfiguration: PubNub.LinearRetryPolicy({
    delay: 1,
    maximumRetry: 10
  })
});

// Subscribe to game lobby
pubnub.subscribe({
  channels: ['game-lobby'],
  withPresence: true
});

Create a Game Room

async function createGameRoom(pubnub, hostPlayerId, gameConfig) {
  const roomId = `game-room-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
  const roomChannel = `game.${roomId}`;
  const stateChannel = `game.${roomId}.state`;

  // Set room metadata via App Context
  await pubnub.objects.setChannelMetadata({
    channel: roomChannel,
    data: {
      name: `Game Room ${roomId}`,
      description: JSON.stringify({
        host: hostPlayerId,
        maxPlayers: gameConfig.maxPlayers || 4,
        gameType: gameConfig.gameType,
        status: 'waiting',
        createdAt: Date.now()
      })
    }
  });

  // Host subscribes to game channels
  pubnub.subscribe({
    channels: [roomChannel, stateChannel],
    withPresence: true
  });

  // Announce room in lobby
  await pubnub.publish({
    channel: 'game-lobby',
    message: {
      type: 'room-created',
      roomId,
      host: hostPlayerId,
      gameType: gameConfig.gameType,
      maxPlayers: gameConfig.maxPlayers || 4
    }
  });

  return { roomId, roomChannel, stateChannel };
}

Synchronize Game State

// Send delta state updates (only changed properties)
async function sendStateUpdate(pubnub, stateChannel, deltaUpdate) {
  await pubnub.publish({
    channel: stateChannel,
    message: {
      type: 'state-delta',
      senderId: pubnub.getUserId(),
      timestamp: Date.now(),
      sequenceNum: ++localSequence,
      delta: deltaUpdate
    }
  });
}

// Listen for state updates and apply them
pubnub.addListener({
  message: (event) => {
    if (event.channel.endsWith('.state')) {
      const { type, delta, sequenceNum, senderId } = event.message;

      if (type === 'state-delta' && senderId !== pubnub.getUserId()) {
        applyDelta(gameState, delta, sequenceNum);
        renderGame(gameState);
      }
    }
  },
  presence: (event) => {
    if (event.action === 'leave' || event.action === 'timeout') {
      handlePlayerDisconnect(event.uuid, event.channel);
    } else if (event.action === 'join') {
      handlePlayerJoin(event.uuid, event.channel);
    }
  }
});

Constraints

MCP Tools

See Also

Output Format

When providing implementations:

  1. Include PubNub SDK initialization with gaming-optimized configuration
  2. Show game room creation and player join/leave lifecycle
  3. Include state synchronization with delta updates and conflict handling
  4. Add presence event handling for disconnect/reconnect scenarios
  5. Note anti-cheat considerations and server-side validation where applicable

Skill frontmatter

license: PubNub metadata: {"author" => "pubnub", "version" => "0.2.0", "domain" => "real-time", "triggers" => "pubnub, multiplayer, gaming, game state, player matching, game rooms, lobby, sync", "role" => "specialist", "scope" => "implementation", "output-format" => "code"}