Leave Standard Room
Leave a Standard Room using the leavestandardroom method. This ensures proper cleanup of resources and notifies other players that you've left the game session.
Method Signature
MoitribeSDK(gameId, 'leavestandardroom', params, callback)
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
onLeftRoom | function | Yes | Callback when room leave is processed |
Examples
Basic Room Leave
Leave the current room with basic cleanup:
- JavaScript
- TypeScript
MoitribeSDK('my-game-id', 'leavestandardroom', {
onLeftRoom: (status, roomID) => {
if (status) {
console.log('✅ Successfully left room:', roomID);
// Clean up game state
cleanupGameState();
// Return to lobby
returnToLobbyScreen();
// Show confirmation
showNotification('Left room successfully', 'success');
// Stop any ongoing timers
clearGameTimers();
// Clear room-specific data
clearRoomData();
} else {
console.error('❌ Failed to leave room');
showNotification('Error leaving room', 'error');
// Force cleanup anyway
forceCleanup();
returnToLobbyScreen();
}
}
}, (result) => {
console.log('Leave room request sent:', result);
// Show leaving indicator
showLeavingIndicator();
// Disable game controls immediately
disableGameControls();
// Pause any ongoing game actions
pauseGameplay();
});
import MoitribeSDK from '@veniso/moitribe-js';
MoitribeSDK('my-game-id', 'leavestandardroom', {
onLeftRoom: (status: boolean, roomID: string) => {
if (status) {
console.log('✅ Successfully left room:', roomID);
// Clean up game state
cleanupGameState();
// Return to lobby
returnToLobbyScreen();
// Show confirmation
showNotification('Left room successfully', 'success');
// Stop any ongoing timers
clearGameTimers();
// Clear room-specific data
clearRoomData();
} else {
console.error('❌ Failed to leave room');
showNotification('Error leaving room', 'error');
// Force cleanup anyway
forceCleanup();
returnToLobbyScreen();
}
}
}, (result) => {
console.log('Leave room request sent:', result);
// Show leaving indicator
showLeavingIndicator();
// Disable game controls immediately
disableGameControls();
// Pause any ongoing game actions
pauseGameplay();
});
Leave with Confirmation Dialog
Show confirmation dialog before leaving:
- JavaScript
- TypeScript
function leaveRoomWithConfirmation() {
// Show confirmation dialog
showConfirmationDialog(
'Leave Room',
'Are you sure you want to leave the room? The game will end for everyone.',
{
confirm: 'Leave',
cancel: 'Stay',
onConfirm: () => {
performRoomLeave();
},
onCancel: () => {
console.log('User cancelled leaving room');
hideConfirmationDialog();
}
}
);
}
function performRoomLeave() {
// Show loading state
showLeavingScreen('Leaving room...');
// Disable user input
disableAllInput();
MoitribeSDK('my-game-id', 'leavestandardroom', {
onLeftRoom: (status, roomID) => {
hideLeavingScreen();
enableAllInput();
if (status) {
console.log('Successfully left room:', roomID);
// Perform comprehensive cleanup
performFullCleanup();
// Return to main menu
navigateToMainMenu();
// Show success message
showToast('You left the room', 'info');
// Log for analytics
logRoomExit(roomID, 'voluntary');
} else {
console.error('Failed to leave room');
// Show error message
showErrorDialog('Unable to leave room', 'Please try again or restart the game');
// Attempt to force leave after delay
setTimeout(() => {
forceLeaveRoom();
}, 3000);
}
}
}, (result) => {
if (result.success) {
console.log('Leave request sent successfully');
} else {
console.error('Failed to send leave request:', result.msg);
hideLeavingScreen();
enableAllInput();
showErrorDialog('Network Error', 'Unable to leave room. Check your connection.');
}
});
}
// Usage
leaveRoomWithConfirmation();
import MoitribeSDK from '@veniso/moitribe-js';
function leaveRoomWithConfirmation(): void {
// Show confirmation dialog
showConfirmationDialog(
'Leave Room',
'Are you sure you want to leave the room? The game will end for everyone.',
{
confirm: 'Leave',
cancel: 'Stay',
onConfirm: () => {
performRoomLeave();
},
onCancel: () => {
console.log('User cancelled leaving room');
hideConfirmationDialog();
}
}
);
}
function performRoomLeave(): void {
// Show loading state
showLeavingScreen('Leaving room...');
// Disable user input
disableAllInput();
MoitribeSDK('my-game-id', 'leavestandardroom', {
onLeftRoom: (status: boolean, roomID: string) => {
hideLeavingScreen();
enableAllInput();
if (status) {
console.log('Successfully left room:', roomID);
// Perform comprehensive cleanup
performFullCleanup();
// Return to main menu
navigateToMainMenu();
// Show success message
showToast('You left the room', 'info');
// Log for analytics
logRoomExit(roomID, 'voluntary');
} else {
console.error('Failed to leave room');
// Show error message
showErrorDialog('Unable to leave room', 'Please try again or restart the game');
// Attempt to force leave after delay
setTimeout(() => {
forceLeaveRoom();
}, 3000);
}
}
}, (result) => {
if (result.success) {
console.log('Leave request sent successfully');
} else {
console.error('Failed to send leave request:', result.msg);
hideLeavingScreen();
enableAllInput();
showErrorDialog('Network Error', 'Unable to leave room. Check your connection.');
}
});
}
// Usage
leaveRoomWithConfirmation();
Leave with Game State Save
Save game progress before leaving:
- JavaScript
- TypeScript
function leaveRoomWithSave() {
// Show saving screen
showSavingScreen('Saving progress and leaving room...');
// Save current game state
saveGameState()
.then(() => {
console.log('Game state saved successfully');
proceedWithLeave();
})
.catch((error) => {
console.error('Failed to save game state:', error);
// Ask user if they want to leave without saving
showConfirmationDialog(
'Save Failed',
'Unable to save game progress. Leave anyway?',
{
confirm: 'Leave Without Saving',
cancel: 'Try Again',
onConfirm: proceedWithLeave,
onCancel: () => {
hideSavingScreen();
retrySave();
}
}
);
});
}
function proceedWithLeave() {
// Update saving screen
updateSavingScreen('Leaving room...');
MoitribeSDK('my-game-id', 'leavestandardroom', {
onLeftRoom: (status, roomID) => {
hideSavingScreen();
if (status) {
console.log('Left room with saved progress:', roomID);
// Final cleanup
performFinalCleanup();
// Return to lobby with save confirmation
returnToLobbyWithSaveConfirmation();
// Show success notification
showNotification('Progress saved and room left', 'success');
} else {
console.error('Failed to leave room after saving');
// Show error but keep saved progress
showErrorDialog('Leave Failed', 'Your progress was saved, but we couldn\'t leave the room. Try again.');
}
}
}, (result) => {
if (result.success) {
console.log('Leave request sent after save');
} else {
console.error('Failed to send leave request:', result.msg);
hideSavingScreen();
showErrorDialog('Network Error', 'Unable to leave room. Your progress is saved locally.');
}
});
}
// Usage
leaveRoomWithSave();
import MoitribeSDK from '@veniso/moitribe-js';
function leaveRoomWithSave(): void {
// Show saving screen
showSavingScreen('Saving progress and leaving room...');
// Save current game state
saveGameState()
.then(() => {
console.log('Game state saved successfully');
proceedWithLeave();
})
.catch((error: Error) => {
console.error('Failed to save game state:', error);
// Ask user if they want to leave without saving
showConfirmationDialog(
'Save Failed',
'Unable to save game progress. Leave anyway?',
{
confirm: 'Leave Without Saving',
cancel: 'Try Again',
onConfirm: proceedWithLeave,
onCancel: () => {
hideSavingScreen();
retrySave();
}
}
);
});
}
function proceedWithLeave(): void {
// Update saving screen
updateSavingScreen('Leaving room...');
MoitribeSDK('my-game-id', 'leavestandardroom', {
onLeftRoom: (status: boolean, roomID: string) => {
hideSavingScreen();
if (status) {
console.log('Left room with saved progress:', roomID);
// Final cleanup
performFinalCleanup();
// Return to lobby with save confirmation
returnToLobbyWithSaveConfirmation();
// Show success notification
showNotification('Progress saved and room left', 'success');
} else {
console.error('Failed to leave room after saving');
// Show error but keep saved progress
showErrorDialog('Leave Failed', 'Your progress was saved, but we couldn\'t leave the room. Try again.');
}
}
}, (result) => {
if (result.success) {
console.log('Leave request sent after save');
} else {
console.error('Failed to send leave request:', result.msg);
hideSavingScreen();
showErrorDialog('Network Error', 'Unable to leave room. Your progress is saved locally.');
}
});
}
// Usage
leaveRoomWithSave();
Emergency Leave (Force Leave)
Force leave when normal leave fails:
- JavaScript
- TypeScript
function emergencyLeave() {
console.log('Performing emergency room leave');
// Show emergency dialog
showEmergencyDialog(
'Emergency Leave',
'Force leaving the room. This may disrupt other players.',
'Force Leave'
);
// Immediately disable all game features
disableAllGameFeatures();
// Clear all timers
clearAllTimers();
// Stop network communications
stopNetworkCommunications();
MoitribeSDK('my-game-id', 'leavestandardroom', {
onLeftRoom: (status, roomID) => {
hideEmergencyDialog();
if (status) {
console.log('Emergency leave successful:', roomID);
} else {
console.warn('Emergency leave failed, but proceeding with cleanup');
}
// Force cleanup regardless of result
forceEmergencyCleanup();
// Return to main menu
forceReturnToMainMenu();
// Log emergency exit
logEmergencyExit(roomID);
}
}, (result) => {
console.log('Emergency leave request sent');
// Don't wait for response - start cleanup immediately
setTimeout(() => {
if (!isCleanupComplete()) {
console.warn('Emergency leave timeout - forcing cleanup');
forceEmergencyCleanup();
forceReturnToMainMenu();
}
}, 5000); // 5 second timeout
});
}
function forceEmergencyCleanup() {
console.log('Performing emergency cleanup');
// Clear all game data
clearAllGameData();
// Reset all variables
resetGlobalVariables();
// Clear local storage
clearTemporaryStorage();
// Reset UI state
resetUIState();
// Stop all animations
stopAllAnimations();
// Clear event listeners
removeAllEventListeners();
// Mark cleanup as complete
setCleanupComplete(true);
}
// Usage in emergency situations
if (gameFrozen || networkLost) {
emergencyLeave();
}
import MoitribeSDK from '@veniso/moitribe-js';
function emergencyLeave(): void {
console.log('Performing emergency room leave');
// Show emergency dialog
showEmergencyDialog(
'Emergency Leave',
'Force leaving the room. This may disrupt other players.',
'Force Leave'
);
// Immediately disable all game features
disableAllGameFeatures();
// Clear all timers
clearAllTimers();
// Stop network communications
stopNetworkCommunications();
MoitribeSDK('my-game-id', 'leavestandardroom', {
onLeftRoom: (status: boolean, roomID: string) => {
hideEmergencyDialog();
if (status) {
console.log('Emergency leave successful:', roomID);
} else {
console.warn('Emergency leave failed, but proceeding with cleanup');
}
// Force cleanup regardless of result
forceEmergencyCleanup();
// Return to main menu
forceReturnToMainMenu();
// Log emergency exit
logEmergencyExit(roomID);
}
}, (result) => {
console.log('Emergency leave request sent');
// Don't wait for response - start cleanup immediately
setTimeout(() => {
if (!isCleanupComplete()) {
console.warn('Emergency leave timeout - forcing cleanup');
forceEmergencyCleanup();
forceReturnToMainMenu();
}
}, 5000); // 5 second timeout
});
}
function forceEmergencyCleanup(): void {
console.log('Performing emergency cleanup');
// Clear all game data
clearAllGameData();
// Reset all variables
resetGlobalVariables();
// Clear local storage
clearTemporaryStorage();
// Reset UI state
resetUIState();
// Stop all animations
stopAllAnimations();
// Clear event listeners
removeAllEventListeners();
// Mark cleanup as complete
setCleanupComplete(true);
}
// Usage in emergency situations
if (gameFrozen || networkLost) {
emergencyLeave();
}
Response Format
The callback receives a response object:
{
success: boolean;
msg?: string; // Error message if failed
}
The onLeftRoom callback receives:
{
status: boolean; // True if leave was successful
roomID: string; // ID of the room you left
}
Cleanup Checklist
When leaving a room, perform these cleanup tasks:
Game State Cleanup
function cleanupGameState() {
// Stop game loop
stopGameLoop();
// Clear game objects
clearGameObjects();
// Reset game variables
resetGameVariables();
// Clear animations
stopAllAnimations();
}
UI Cleanup
function cleanupUI() {
// Hide game screens
hideGameScreens();
// Clear player lists
clearPlayerList();
// Reset UI state
resetUIState();
// Clear notifications
clearNotifications();
}
Network Cleanup
function cleanupNetwork() {
// Clear message handlers
clearMessageHandlers();
// Stop network polling
stopNetworkPolling();
// Clear connection data
clearConnectionData();
}
Audio Cleanup
function cleanupAudio() {
// Stop all sounds
stopAllSounds();
// Clear audio buffers
clearAudioBuffers();
// Reset audio state
resetAudioState();
}
Leave Scenarios
Voluntary Leave
- Player chooses to leave via UI
- Show confirmation dialog
- Save game progress if needed
- Perform graceful cleanup
Involuntary Leave
- Network disconnection
- Game crash or error
- Server-initiated kick
- Perform emergency cleanup
Game End Leave
- Natural game conclusion
- Show results screen
- Save final scores
- Return to lobby
Error Handling
Common errors and solutions:
| Error | Cause | Solution |
|---|---|---|
Not in room | Player not connected to room | Check room state before leaving |
Network error | Connection issues | Implement retry logic |
Leave timeout | Server not responding | Force leave after timeout |
Cleanup failed | Resource cleanup issues | Force cleanup and restart |
warning
Always implement proper cleanup when leaving a room. Incomplete cleanup can cause memory leaks, UI glitches, or connection issues in subsequent sessions.
Best Practices
User Experience
- Show clear confirmation dialogs
- Provide progress indicators
- Explain what's happening during leave
- Offer retry options on failures
Data Integrity
- Save game progress before leaving
- Verify save completion
- Handle save failures gracefully
- Maintain data consistency
Performance
- Clean up resources efficiently
- Avoid memory leaks
- Stop unnecessary processes
- Reset state completely
Error Recovery
- Implement retry mechanisms
- Provide fallback options
- Log errors for debugging
- Handle edge cases gracefully