Loading...
Loading...
Compare original and translation side by side
| 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 |
| 参考文档 | 用途 |
|---|---|
| gaming-setup.md | 游戏房间创建、大厅管理以及PubNub初始化 |
| gaming-state-sync.md | 游戏状态同步、增量更新以及冲突解决 |
| gaming-patterns.md | 玩家匹配、回合制/实时游戏模式、反作弊以及排行榜 |
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
});import PubNub from 'pubnub';
const pubnub = new PubNub({
publishKey: 'pub-c-...',
subscribeKey: 'sub-c-...',
userId: 'player-abc-123',
presenceTimeout: 20, // 快速检测玩家断开连接
heartbeatInterval: 10, // 游戏场景下的高频心跳
restore: true, // 连接丢失时自动重连
retryConfiguration: PubNub.LinearRetryPolicy({
delay: 1,
maximumRetry: 10
})
});
// 订阅游戏大厅频道
pubnub.subscribe({
channels: ['game-lobby'],
withPresence: true
});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 };
}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`;
// 通过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()
})
}
});
// 房主订阅游戏频道
pubnub.subscribe({
channels: [roomChannel, stateChannel],
withPresence: true
});
// 在大厅中发布房间创建通知
await pubnub.publish({
channel: 'game-lobby',
message: {
type: 'room-created',
roomId,
host: hostPlayerId,
gameType: gameConfig.gameType,
maxPlayers: gameConfig.maxPlayers || 4
}
});
return { roomId, roomChannel, stateChannel };
}// 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);
}
}
});// 发送增量状态更新(仅包含变更的属性)
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
}
});
}
// 监听状态更新并应用到游戏中
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);
}
}
});