Skip to content

File PlayerSlotState.hpp

File List > Engine > include > Resources > PlayerSlotState.hpp

Go to the documentation of this file

#ifndef ENGINE_RESOURCES_PLAYERSLOTSTATE_HPP_
#define ENGINE_RESOURCES_PLAYERSLOTSTATE_HPP_

#include <cstddef>
#include <cstdint>
#include <optional>
#include <unordered_map>
#include <unordered_set>

namespace Engine::Multiplayer {

struct PlayerSlotState {
    static inline std::uint8_t kMaxPlayers = 5;

    std::unordered_map<std::size_t, std::uint8_t> byNetworkId;

    std::optional<std::uint8_t> Assign(std::size_t networkId) {
        std::unordered_set<std::uint8_t> used;
        used.reserve(byNetworkId.size());
        for (const auto& [id, slot] : byNetworkId) {
            used.insert(slot);
        }
        for (std::uint8_t slot = 0; slot < kMaxPlayers; ++slot) {
            if (!used.contains(slot)) {
                byNetworkId[networkId] = slot;
                return slot;
            }
        }
        return std::nullopt;
    }

    void Release(std::size_t networkId) {
        byNetworkId.erase(networkId);
    }

    std::optional<std::uint8_t> Get(std::size_t networkId) const {
        const auto it = byNetworkId.find(networkId);
        if (it == byNetworkId.end()) {
            return std::nullopt;
        }
        return it->second;
    }
};

} // namespace Engine::Multiplayer

#endif // ENGINE_RESOURCES_PLAYERSLOTSTATE_HPP_