Working with Data

Saving in Multiplayer Games

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

Abstract art representing computer programming

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.

Answers to questions are automatically generated and may not have been reviewed.

sdl2-promo.jpg
Part of the course:

Game Dev with SDL2

Learn C++ and SDL development by creating hands on, practical projects inspired by classic retro games

Free, unlimited access

This course includes:

  • 75 Lessons
  • 100+ Code Samples
  • 91% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2025 - All Rights Reserved