Saving in Multiplayer Games

For multiplayer games, how do we handle saving when multiple players can modify the same object?

Handling saves in multiplayer games requires careful consideration of authority and synchronization. Here's how it's typically managed:

Authority Model

First, establish which instance of the game has authority over each object:

class GameObject {
  int OwnerId; // Player with authority
  Vector2 Position;
  bool IsDirty; // Track if object needs saving

public:
  bool HasAuthority(int PlayerId) const {
    return PlayerId == OwnerId;
  }

  void UpdatePosition(const Vector2& NewPos,
                      int RequestingPlayer) {
    if (HasAuthority(RequestingPlayer)) {
      Position = NewPos;
      IsDirty = true;
      BroadcastUpdate(); // Tell other players
    }
  }
};

Conflict Resolution

When multiple players can modify an object, implement conflict resolution:

struct Modification {
  int PlayerId;
  int ObjectId;
  // Use server time for consistency
  int Timestamp;
  Vector2 NewPosition;
};

class ConflictResolver {
 public:
  void HandleModification(
    const Modification& Mod
  ) {
    auto& Object = GetObject(Mod.ObjectId);

    if (Mod.Timestamp > Object.LastModified) {
      // Accept newer modification
      Object.Position = Mod.NewPosition;
      Object.LastModified = Mod.Timestamp;
    }
  }
};

Server-Side Saving

In most cases, the authoritative server handles saving:

class GameServer {
  std::unordered_map<int, GameObject> Objects;

  void SaveGameState() {
    GameState State;

    for (const auto& [Id, Object] : Objects) {
      if (Object.IsDirty) {
        State.ModifiedObjects.push_back(Object);
      }
    }

    if (!State.ModifiedObjects.empty()) {
      WriteToDatabase(State);
    }
  }
};

This approach ensures consistency and prevents cheating, while maintaining responsive gameplay.

Working with Data

Learn techniques for managing game data, including save systems, configuration, and networked multiplayer.

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Managing Save File Versions
Is it possible to update my game without breaking existing save files from older versions?
Preventing Save File Tampering
What happens if a player tries to cheat by editing the save file? How can we prevent that?
Managing Large Save Files
How do professional games handle really large save files, like open world games with lots of player progress?
Cross-Platform Save Files
In real games, how do developers manage compatibility between different platforms' save files?
Implementing Autosave
How do games typically handle automatic saving? Should we save after every player action?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant