MultiplayerController
TheMultiplayerController is the heart of Grimoire Infini’s multiplayer system. It manages real-time synchronization of game state, player actions, and card movements using Firebase Firestore.
Overview
The MultiplayerController handles:- Real-time game state synchronization
- Player action broadcasting
- Card position and state management
- Firebase Firestore integration
Key Features
Real-time Sync
Automatic synchronization of game state across all connected players
Action System
Efficient action-based updates for optimal performance
State Management
Centralized game state stored in Firebase Firestore
Error Handling
Robust error handling and connection recovery
Architecture
Basic Usage
Initialization
Moving Cards
Flipping Cards
Cleanup
Core Interfaces
GameState
The central game state structure:CardState
Represents the state of a single card:GameAction
Represents player actions:Implementation Details
Real-time Listeners
The controller sets up two main Firebase listeners:- Game State Listener: Monitors changes to the overall game state
- Actions Listener: Listens for new player actions in real-time
Action Broadcasting
When a player performs an action, it’s broadcast to all other players:Position Optimization
To prevent jitter from minor position changes, the controller uses a threshold system:Best Practices
Initialize Once
Initialize Once
Create only one MultiplayerController instance per game session. Multiple instances can cause conflicts and duplicate listeners.
Always Dispose
Always Dispose
Call
dispose() when leaving the game to clean up Firebase listeners and prevent memory leaks.Handle Errors
Handle Errors
Wrap multiplayer operations in try-catch blocks to handle network issues gracefully.
Optimize Actions
Optimize Actions
Batch related actions together and avoid sending too many rapid updates.
Advanced Usage
Custom Action Types
You can extend the system with custom action types:Room Management
For advanced room management, you can extend the controller:Troubleshooting
Actions not synchronizing
Actions not synchronizing
- Check Firebase security rules
- Verify all players are in the same room
- Ensure proper error handling is in place
- Check browser console for connection errors
Memory leaks
Memory leaks
- Always call
dispose()when done - Check for multiple controller instances
- Verify listeners are properly unsubscribed
Performance issues
Performance issues
- Implement action throttling for rapid updates
- Use position thresholds to reduce unnecessary updates
- Consider batching multiple state changes
