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:

  1. Use the game ID to load the current game state from Cloud Save.
  2. Verify that it’s the correct player’s turn.
  3. Check that the piece at the start position matches the request.
  4. Validate that the piece can legally move to the end position.
  5. Move the piece to update the board state.
  6. Calculate if the piece captures an opponent piece.
  7. Check for checkmate and end the game if true.
  8. Save the updated board state to Cloud Save.
  9. Emit a real time update with a push message to notify the opponent of the move.
  10. Return a response to the player’s client that Cloud Code processed the move.