> ## Documentation Index
> Fetch the complete documentation index at: https://devdocs.xbox.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Démarrage rapide du SDK Matchmaking

> Présentation pas à pas du flux client de matchmaking du SDK PlayFab Multiplayer : initialiser la bibliothèque, soumettre un ticket et recevoir les résultats de correspondance.

Ce guide de démarrage rapide vous guide tout au long du processus d'ajout du matchmaking à votre jeu à l'aide du SDK PlayFab Multiplayer.

Ce tutoriel montre comment soumettre un ticket à une file d'attente spécifique afin de trouver une partie. Une file d'attente correspond généralement à un mode de jeu ou à plusieurs modes de jeu (par exemple, un mode capture du drapeau et un mode roi de la colline dans la même file d'attente).

Le service de matchmaking se charge de trouver une correspondance parmi les tickets d'une file d'attente. Lorsqu'une correspondance est trouvée, votre titre doit se charger de connecter les joueurs entre eux pour jouer.

<Note>
  Le SDK PlayFab Multiplayer fournit également des API pour les lobbies PlayFab. \* Pour plus d'informations sur les API C++, consultez le [Démarrage rapide du SDK Lobby](/fr-CA/services/playfab/multiplayer/lobby/lobby-getting-started) \* Pour plus d'informations sur les API Unity, consultez le [Démarrage rapide pour Unity](/fr-CA/services/playfab/multiplayer/lobby/lobby-matchmaking-sdks/multiplayer-unity-sdk-getting-started) \* Pour plus d'informations sur les API Unreal, consultez le [Démarrage rapide pour Unreal](/fr-CA/services/playfab/multiplayer/networking/party-unreal-engine-oss-quickstart)
</Note>

## Prérequis

Vous avez besoin d'un [compte PlayFab](https://developer.playfab.com) pour utiliser PlayFab Matchmaking. Pour obtenir des instructions sur la création d'un compte, consultez [Démarrage rapide : Game Manager](/fr-CA/services/playfab/live-service-management/gamemanager/quickstart).

## Configurer une file d'attente de matchmaking dans Game Manager

La bibliothèque met en correspondance les utilisateurs qui créent des tickets pour des files d'attente configurées dans Game Manager. Pour plus de détails sur la configuration d'une file d'attente, consultez [Configuration des files d'attente de matchmaking](/fr-CA/services/playfab/multiplayer/matchmaking/config-queues).

## Télécharger et configurer le SDK PlayFab Multiplayer

Téléchargez le [SDK C/C++](/fr-CA/services/playfab/multiplayer/lobby/lobby-matchmaking-sdks/lobby-matchmaking-sdks) pour votre plateforme et intégrez l'en-tête du fournisseur et les fichiers de bibliothèque à votre build.

<Note>
  Ce démarrage rapide porte sur l'utilisation du SDK C/C++. Pour les interfaces Unity et Unreal, consultez les articles suivants : \* [Démarrage rapide pour Unity](/fr-CA/services/playfab/multiplayer/lobby/lobby-matchmaking-sdks/multiplayer-unity-sdk-getting-started) \* [Démarrage rapide pour Unreal](/fr-CA/services/playfab/multiplayer/networking/party-unreal-engine-oss-quickstart)
</Note>

## Connecter une entité PlayFab

Pour utiliser le SDK PlayFab Lobby, vous devez authentifier votre client à l'aide de clés d'entité et de jetons d'entité PlayFab. Obtenez une paire clé d'entité/jeton PlayFab en vous connectant avec l'API REST [LoginWithCustomId](https://learn.microsoft.com/en-us/rest/api/playfab/client/authentication/login-with-custom-id). Cette API est également disponible sous forme de projection C/C++ au moyen du [SDK REST PlayFab](/fr-CA/services/playfab/sdks/playfab-sdk-intro).

<Note>
  LoginWithCustomId est un moyen rapide de commencer à utiliser les fonctionnalités PlayFab, mais il ne s'agit pas du mécanisme de connexion à utiliser dans votre jeu publié. Pour obtenir des conseils sur la connexion, consultez [Principes de base et pratiques exemplaires de connexion](/fr-CA/services/playfab/identity/player-identity/login/login-basics-best-practices).
</Note>

## Initialiser le SDK PlayFab Multiplayer

Initialisez le SDK PlayFab Multiplayer en suivant ces étapes de base :

1. Initialisez le SDK en appelant [PFMultiplayerInitialize](/fr-CA/services/playfab/multiplayer/lobby/playfabmultiplayerreference-cpp/pfmultiplayer/functions/pfmultiplayerinitialize)
2. Définissez la clé d'entité et le jeton utilisés par la bibliothèque pour le compte de vos joueurs en appelant [PFMultiplayerSetEntityToken](/fr-CA/services/playfab/multiplayer/lobby/playfabmultiplayerreference-cpp/pfmultiplayer/functions/pfmultiplayersetentitytoken).

```cpp theme={null}
static PFMultiplayerHandle g_pfmHandle = nullptr;
...
...
HRESULT hr = S_OK;

// Initialize the PFMultiplayer library.
hr = PFMultiplayerInitialize(titleId, &g_pfmHandle);
if (FAILED(hr))
{
    // handle initialize failure
}

// Set an entity token for a local user. The token is used to authenticate PlayFab operations on behalf of this user. 
// Tokens can expire, and this API token should be called again when this token is refreshed.
hr = PFMultiplayerSetEntityToken(g_pfmHandle, localUserEntity, entityToken);
if (FAILED(hr))
{
    // handle set entity token failure
}
```

## Créer un ticket de matchmaking

Vous créez un ticket de matchmaking à l'aide de [PFMultiplayerCreateMatchmakingTicket](/fr-CA/services/playfab/multiplayer/lobby/playfabmultiplayerreference-cpp/pfmatchmaking/functions/pfmultiplayercreatematchmakingticket), en spécifiant tous les utilisateurs locaux qui doivent faire partie de la correspondance et tous les attributs que vous souhaitez associer à ces utilisateurs.

Cette fonction prend également une structure [PFMatchmakingTicketConfiguration](/fr-CA/services/playfab/multiplayer/lobby/playfabmultiplayerreference-cpp/pfmatchmaking/structs/pfmatchmakingticketconfiguration) dans laquelle vous spécifiez la file d'attente à laquelle le ticket est destiné, un délai d'expiration pour le ticket et les utilisateurs distants que vous souhaitez inclure dans ce ticket.

### Matchmaking avec un seul utilisateur local

Vous pouvez démarrer le matchmaking pour un seul utilisateur local en appelant **PFMultiplayerCreateMatchmakingTicket**.

```cpp theme={null}
const char* yourQueueName = ...; // This is the name of the queue you configured in Game Manager.

PFMatchmakingTicketConfiguration configuration{};
configuration.timeoutInSeconds = 120;
configuration.queueName = yourQueueName;

const char* attributes = "\"{\"color\":\"blue\", \"role\":\"tank\"}\"";

const PFMatchmakingTicket* ticket;
HRESULT hr = PFMultiplayerCreateMatchmakingTicket(
    g_pfmHandle,
    1, // number of local users
    localUserEntity,
    &attributes,
    &configuration,
    nullptr, // optional asyncContext
    &ticket);
RETURN_IF_FAILED(hr);
```

### Matchmaking avec un groupe d'utilisateurs distants

Pour démarrer un matchmaking de groupe avec des utilisateurs distants, il est utile de considérer l'un des clients comme le chef. Demandez au chef de créer le ticket à l'aide de **PFMultiplayerCreateMatchmakingTicket**, en spécifiant les autres utilisateurs du groupe au moyen du paramètre **configuration**. Une fois le ticket créé, appelez **GetTicketId** pour obtenir l'ID du ticket. Envoyez cet ID à chacun des autres utilisateurs par un mécanisme externe, comme un maillage réseau ou un lobby PlayFab partagé, et demandez à chaque client d'appeler **PFMultiplayerJoinMatchmakingTicketFromId** avec l'ID du ticket pour rejoindre le ticket de matchmaking. L'état du ticket est **PFMatchmakingTicketStatus::WaitingForPlayers** pendant l'attente des joueurs spécifiés, puis passe à **PFMatchmakingTicketStatus::WaitingForMatch** une fois que tous les joueurs ont rejoint le ticket.

```cpp theme={null}
// Creating the ticket on the leader's client

const char* remoteMemberEntityId1 = ...;
const char* remoteMemberEntityId2 = ...;

std::vector<PFEntityKey> remoteMatchMemberEntityKeys;
remoteMatchMemberEntityKeys.push_back({ remoteMemberEntityId1, "title_player_account" });
remoteMatchMemberEntityKeys.push_back({ remoteMemberEntityId2, "title_player_account" });

const char* yourQueueName = ...; // This is the name of the queue you configured in Game Manager.

PFMatchmakingTicketConfiguration configuration{};
configuration.timeoutInSeconds = 120;
configuration.queueName = yourQueueName;
configuration.membersToMatchWithCount = 2; // number of remote members to match with
configuration.membersToMatchWith = remoteMatchMemberEntityKeys.data();

const char* attributes = "\"{\"color\":\"blue\", \"role\":\"tank\"}\"";

const PFMatchmakingTicket* ticket;
HRESULT hr = PFMultiplayerCreateMatchmakingTicket(
    g_pfmHandle,
    1, // number of local users
    localUserEntity,
    &attributes,
    &configuration,
    nullptr, // optional asyncContext
    &ticket);
RETURN_IF_FAILED(hr);

// Getting the ticket ID

PCSTR ticketId;
hr = PFMatchmakingTicketGetTicketId(ticket, &ticketId);
RETURN_IF_FAILED(hr);
```

```cpp theme={null}
// Joining the ticket on the other players' clients

const char* attributes = "\"{\"color\":\"blue\", \"role\":\"healer\"}\"";
const char* yourQueueName = ...; // This is the name of the queue you configured in Game Manager.

const PFMatchmakingTicket* ticket;
HRESULT hr = PFMultiplayerJoinMatchmakingTicketFromId(
    g_pfmHandle,
    1, // number of local users
    localUserEntity,
    &attributes,
    ticketId,
    yourQueueName,
    nullptr, // optional asyncContext
    &ticket);
```

### Matchmaking avec plusieurs utilisateurs locaux

Lors d'un matchmaking avec plusieurs utilisateurs locaux, au lieu de transmettre une seule **PFEntityKey** aux fonctions **PFMultiplayerCreateMatchmakingTicket** ou **PFMultiplayerJoinMatchmakingTicketFromId**, vous devez transmettre une liste de clés. De même, vous devez transmettre une liste d'attributs pour chaque utilisateur. Les positions des entrées de chaque liste doivent se correspondre. Autrement dit, la première entrée de la liste des attributs doit correspondre aux attributs du premier joueur de la liste **PFEntityKey**.

```cpp theme={null}
const char* yourQueueName = ...; // This is the name of the queue you configured in Game Manager.

PFMatchmakingTicketConfiguration configuration{};
configuration.timeoutInSeconds = 120;
configuration.queueName = queueName;

std::vector<PFEntityKey> localMatchMemberEntityKeys{ ... };
std::vector<PCSTR> localMatchMemberAttributes{ ... };

const PFMatchmakingTicket* ticket;
HRESULT hr = PFMultiplayerCreateMatchmakingTicket(
    g_pfmHandle,
    static_cast<uint32_t>(localMatchMemberEntityKeys.size())
    localMatchMemberEntityKeys.data(),
    localMatchMemberAttributes.data(),
    &configuration,
    nullptr, // optional asyncContext
    &ticket);
RETURN_IF_FAILED(hr);
```

## Vérifier l'état du ticket de matchmaking

Vous devez vérifier les mises à jour du ticket en appelant [PFMultiplayerStartProcessingMatchmakingStateChanges](/fr-CA/services/playfab/multiplayer/lobby/playfabmultiplayerreference-cpp/pfmatchmaking/functions/pfmultiplayerstartprocessingmatchmakingstatechanges) pour recevoir les changements d'état, puis en appelant [PFMultiplayerFinishProcessingMatchmakingStateChanges](/fr-CA/services/playfab/multiplayer/lobby/playfabmultiplayerreference-cpp/pfmatchmaking/functions/pfmultiplayerfinishprocessingmatchmakingstatechanges) lorsque vous avez terminé de traiter ces changements d'état.

Le SDK retourne un changement d'état **TicketStatusChanged** chaque fois que l'état du ticket change, et un changement d'état **TicketCompleted** lorsque le matchmaking est terminé.

### Exemple d'utilisation du SDK client Matchmaking

```cpp theme={null}
HRESULT hrTicketError = S_OK;

uint32_t stateChangeCount;
const PFMatchmakingStateChange * const * stateChanges;
hr = PFMultiplayerStartProcessingMatchmakingStateChanges(g_pfmHandle, &stateChangeCount, &stateChanges);
RETURN_IF_FAILED(hr);

for (uint32_t i = 0; i < stateChangeCount; ++i)
{
    const PFMatchmakingStateChange& stateChange = *stateChanges[i];

    switch (stateChange.stateChangeType)
    {
        case PFMatchmakingStateChangeType::TicketStatusChanged:
        {
            const auto& ticketStatusChanged = static_cast<const PFMatchmakingTicketStatusChangedStateChange&>(stateChange);

            PFMatchmakingTicketStatus status;
            if (SUCCEEDED(PFMatchmakingTicketGetStatus(ticketStatusChanged.ticket, &status)))
            {
                printf("Ticket status is now: %i.\n", status);
            }

            break;
        }
        case PFMatchmakingStateChangeType::TicketCompleted:
        {
            const auto& ticketCompleted = static_cast<const PFMatchmakingTicketCompletedStateChange&>(stateChange);

            printf("PFMatchmaking completed with Result 0x%08x.\n", ticketCompleted.result);

            if (FAILED(ticketCompleted.result))
            {
                // On failure, we must record the HRESULT so we can return the state change(s) and then bail
                // out of this function.
                hrTicketError = ticketCompleted.result;
            }

            break;
        }
    }
}

hr = PFMultiplayerFinishProcessingMatchmakingStateChanges(g_pfmHandle, stateChangeCount, stateChanges);
RETURN_IF_FAILED(hr);

// Now that we've returned the state change(s), bail out if we detected ticket failure.
RETURN_IF_FAILED(hrTicketError);
```

## Obtenir la correspondance

Après avoir reçu le changement d'état **PFMatchmakingStateChangeType::TicketCompleted**, appelez [PFMatchmakingTicketGetMatch](/fr-CA/services/playfab/multiplayer/lobby/playfabmultiplayerreference-cpp/pfmatchmaking/functions/pfmatchmakingticketgetmatch) pour obtenir les détails de la correspondance. Ces détails contiennent l'ID de la correspondance, les utilisateurs qui ont été mis en correspondance, la région préférée pour la correspondance et une chaîne d'arrangement pour le lobby associé à la correspondance.

Une fois que vous avez récupéré les informations dont vous avez besoin dans la structure **PFMatchmakingMatchDetails**, le ticket doit être détruit avec [PFMultiplayerDestroyMatchmakingTicket](/fr-CA/services/playfab/multiplayer/lobby/playfabmultiplayerreference-cpp/pfmatchmaking/functions/pfmultiplayerdestroymatchmakingticket).

### Exemple d'utilisation du SDK client Matchmaking

```cpp theme={null}
const PFMatchmakingMatchDetails* match;
HREULT hr = PFMatchmakingTicketGetMatch(ticket, &match);
RETURN_IF_FAILED(hr);

std::string matchId = match->matchId;
std::string lobbyArrangementString = match->lobbyArrangementString;

PFMultiplayerDestroyMatchmakingTicket(g_pfmHandle, ticket);
```

## Annulation d'un ticket de matchmaking

Si, pour une raison quelconque, votre client souhaite annuler le processus de matchmaking avant l'expiration du délai défini dans la `PFMatchmakingTicketConfiguration`, appelez [PFMatchmakingTicketCancel](/fr-CA/services/playfab/multiplayer/lobby/playfabmultiplayerreference-cpp/pfmatchmaking/functions/pfmatchmakingticketcancel) avec le handle du ticket.

L'appel de cette API ne garantit pas l'annulation du ticket. Le ticket peut encore se terminer avant que l'annulation puisse être traitée, ou la demande d'annulation peut échouer en raison d'erreurs réseau ou de service. Vous pouvez toujours traiter les changements d'état du matchmaking pour obtenir le résultat du ticket si vous souhaitez confirmer que l'annulation du ticket est terminée avant de continuer. Sinon, vous pouvez appeler immédiatement [PFMultiplayerDestroyMatchmakingTicket](/fr-CA/services/playfab/multiplayer/lobby/playfabmultiplayerreference-cpp/pfmatchmaking/functions/pfmultiplayerdestroymatchmakingticket).

### Exemple d'utilisation du SDK client Matchmaking

```cpp theme={null}
HRESULT hr = PFMatchmakingTicketCancel(ticket);

PFMultiplayerDestroyMatchmakingTicket(g_pfmHandle, ticket);
```

## (Facultatif) Réunir vos joueurs dans un lobby

Une fois vos joueurs mis en correspondance, ils peuvent se retrouver ensemble dans un lobby. La structure **PFMatchmakingMatchDetails** du ticket mis en correspondance contient un champ **lobbyArrangementString**, qui peut être utilisé pour réunir les utilisateurs dans le même lobby.

Pour plus d'informations sur l'interaction entre Lobby et Matchmaking, consultez [Utiliser le lobby et le matchmaking ensemble](/fr-CA/services/playfab/multiplayer/lobby/lobby-and-matchmaking).

Pour plus d'informations sur les lobbies PlayFab, consultez la [Vue d'ensemble de PlayFab Lobby](/fr-CA/services/playfab/multiplayer/lobby).

### Exemple d'utilisation du SDK client Matchmaking

```cpp theme={null}
const PFMatchmakingMatchDetails* match;
HREULT hr = PFMatchmakingTicketGetMatch(ticket, &match);
RETURN_IF_FAILED(hr);

std::string matchId = match->matchId;
std::string lobbyArrangementString = match->lobbyArrangementString;

PFMultiplayerDestroyMatchmakingTicket(g_pfmHandle, ticket);

PFLobbyHandle lobby;
RETURN_IF_FAILED_HR(PFMultiplayerJoinArrangedLobby(
    m_pfmHandle,
    &joiningUser,
    lobbyArrangementString,
    &joinConfig,
    nullptr, // optional asyncContext
    &lobby));
```

## Conclusion

Grâce à ce démarrage rapide, vous devriez maintenant disposer d'un flux de matchmaking fonctionnel dans votre jeu. Vous devez également tenir compte des points suivants :

* La façon dont votre titre gère la formation des groupes.
* Ce que votre titre affiche pendant que les utilisateurs attendent une correspondance.
* La façon de gérer les échecs et les nouvelles tentatives.

## Voir aussi

* [SDK Lobby](/fr-CA/services/playfab/multiplayer/lobby/lobby-getting-started)


## Related topics

- [Démarrage rapide du SDK Lobby](/fr-CA/services/playfab/multiplayer/lobby/lobby-getting-started.md)
- [SDK PlayFab Lobby et Matchmaking](/fr-CA/services/playfab/multiplayer/lobby/lobby-matchmaking-sdks/lobby-matchmaking-sdks.md)
- [Démarrage rapide du matchmaking](/fr-CA/services/playfab/multiplayer/matchmaking/quickstart.md)
- [Démarrage rapide du plugiciel Multiplayer pour Unity](/fr-CA/services/playfab/multiplayer/lobby/lobby-matchmaking-sdks/multiplayer-unity-plugin-quickstart.md)
- [Démarrage rapide](/fr-CA/services/playfab/economy-monetization/economy-v2/quickstart.md)
