Game state management
To implement server authority, you can model the full game state on a backend server. This means that each player client acts as a view port while the server enforces rules, validation and cheat prevention. You can store game state data in a Cloud Save to ensure that the game is persistent across clients and can resume from any point.
Server game state management is a robust way to build asynchronous multiplayer games as you leverage the cloud server as the source of truth while clients handle presentation. The client can focus on smooth UI and visualization, while the server manages game play, integrity, and synchronization.
Chess example
For a game like chess, the server can maintain the authoritative board and piece positions in Cloud Code and Cloud Save. When a player makes a move, their client sends a request to a Cloud Code function with parameters such as:
- Game ID
- Piece moved
- Starting position
- Ending position
The Cloud Code function for a chess game can do the following each turn:
- Use the game ID to load the current game state from Cloud Save.
- Verify that it’s the correct player’s turn.
- Check that the piece at the start position matches the request.
- Validate that the piece can legally move to the end position.
- Move the piece to update the board state.
- Calculate if the piece captures an opponent piece.
- Check for checkmate and end the game if true.
- Save the updated board state to Cloud Save.
- Emit a real time update with a push message to notify the opponent of the move.
- Return a response to the player’s client that Cloud Code processed the move.