> ## 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.

# Azure Functions を使用したリーダーボード

> Azure Functions CloudScript を使って PlayFab リーダーボードを構築するチュートリアル。サーバー側のコードからスコアを送信し、ランキングをクエリする方法を示します。

このチュートリアルでは、Cloudscript、特に [Azure Functions](/services/playfab/live-service-management/service-gateway/automation/cloudscript-af) を使用してリーダーボードを実装する方法を学びます。このアプローチは、クライアントの更新を必要とせずにカスタムのサーバー側ロジックを作成できるという点で強力です。

Azure Function 内でリーダーボード関連のロジックを定義することで、クライアントがその関数を呼び出してコードを実行できます。後で変更が必要になった場合は、更新の複雑さにもよりますが、多くの場合クライアントを変更せずに、Azure Function を単独で更新できます。

## 前提条件

このチュートリアルに従うには、次のものが必要です:

* PlayFab アカウント。持っていない場合は、[こちら](https://developer.playfab.com/)で作成できます。
* Azure サブスクリプション。持っていない場合は、[こちら](https://azure.microsoft.com/free/)で作成できます。

Azure Function の作成方法の詳細については、こちらのガイドを参照してください: [Visual Studio を使用して Azure で最初の関数を作成する](https://learn.microsoft.com/azure/azure-functions/functions-create-your-first-function-visual-studio)

## Azure Functions を使用してリーダーボードを作成する

このセクションでは、スコアを送信し、上位スコアを取得できるリーダーボードを作成します。

```C# theme={null}
[Function("LeaderboardExample")]
public async Task<HttpResponseData> RunAsync([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestData req)
{
    _logger.LogInformation("C# HTTP trigger function processed a request.");

    PlayFabSettings.staticSettings.TitleId = "78C3E"; // Change this value to your own titleId from PlayFab Game Manager
    PlayFabSettings.staticSettings.DeveloperSecretKey = "WJT5SBP7PUFH61JHE39QQ4F1SJKGBWBJR647CH1WYB9CS3MZDD"; // Change this to your title's secret key from Game Manager
                                                                                                              // Check if parameter exists
    if (string.IsNullOrEmpty(req.Query["leaderboardName"]))
    {
        var badResponse = req.CreateResponse(HttpStatusCode.BadRequest);
        badResponse.Headers.Add("Content-Type", "text/plain; charset=utf-8");
        badResponse.WriteString("Please pass a leaderboardName on the query string");
        return badResponse;
    }

    PlayFabAuthenticationContext authContext = await LoginAsTitleEntity();
    var result = await CreateLeaderboardDefinitionAsync(authContext, req.Query["leaderboardName"]);
    if (result != null)
    {
        if (result.Error != null) {
            PlayFabError apiError = result.Error;
            var response = req.CreateResponse(HttpStatusCode.BadRequest);
            response.Headers.Add("Content-Type", "text/plain; charset=utf-8");
            if (apiError != null)
            {
                response.WriteString("Something went wrong with your API call.  :");
                response.WriteString("Here's some debug information:");
                response.WriteString(PlayFabUtil.GenerateErrorReport(apiError));
                return response;
            }
            response.WriteString("Something went wrong with your API call but it wasn't possible to get a PlayFab error description.");
            return response;
        }
        else
        {
            var response = req.CreateResponse(HttpStatusCode.OK);
            response.Headers.Add("Content-Type", "text/plain; charset=utf-8");
            response.WriteString("Leaderboard created successfully!");
            return response;
        }
    }
    else 
    {
        var response = req.CreateResponse(HttpStatusCode.BadRequest);
        response.Headers.Add("Content-Type", "text/plain; charset=utf-8");
        response.WriteString("Something went wrong with your API call.  :");
        return response;
    }    
    
}

```

* 関数属性 `[Function("LeaderboardExample")]` は、この関数の名前 (この場合は `LeaderboardExample`) を定義します。
* この関数は、`[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")]` 属性で示されるとおり、HTTP 要求によってトリガーされます。つまり、この関数は認証なしで HTTP GET および POST メソッド経由でアクセスできます。
* 関数内では、PlayFab サービスへの要求を認証するために PlayFab のタイトル ID と開発者シークレット キーを設定します。これらの値へのアクセス方法は、具体的なケースやセキュリティ要件に最適なものに応じて変更できます。
* 関数は、要求のクエリ パラメーター "leaderboardName" が提供されているかどうかを確認します。
* 次に `LoginAsTitleEntity` メソッドを呼び出して、タイトル エンティティとして認証します。これはリーダーボード定義の作成に必要です。
* 最後に `CreateLeaderboardDefinitionAsync` メソッドを呼び出して、指定された名前でリーダーボード定義を作成します。リーダーボードの作成の詳細については、[基本的なリーダーボードを作成する](/services/playfab/community/leaderboards/create-basic-leaderboard)および[リーダーボードでさらにできること](/services/playfab/community/leaderboards/doing-more-with-leaderboards)を参照してください。

RunAsync メソッドは Azure Function のエントリ ポイントとして機能します。ここから、追加のメソッドを定義して呼び出して、カスタム ゲーム ロジックを構築できます。エラーの処理方法や複数の PlayFab サービスとのやり取り方法は完全にあなた次第であり、実装において全面的な柔軟性が得られます。

さらに、特定のイベントに基づいてこの Azure Function をトリガーするための自動化ルールを構成できます。詳細については[こちら](/services/playfab/live-service-management/service-gateway/automation/cloudscript-af/quickstart)を参照してください。

## 関連項目

* [リーダーボードでさらにできること](/services/playfab/community/leaderboards/doing-more-with-leaderboards)
* [基本的なリーダーボードを作成する](/services/playfab/community/leaderboards/create-basic-leaderboard)
* [手動ティア](/services/playfab/community/leaderboards/manual-tiers)
* [制限](/services/playfab/community/leaderboards/limits-leaderboards)
* [クォータ](/services/playfab/community/leaderboards/quota-leaderboards)
* [シーズナル リーダーボード](/services/playfab/community/leaderboards/seasonal-leaderboards)
* [統計によってプレイヤーをランキング付けする](/services/playfab/community/leaderboards/leaderboards-linked-to-stats)
* [リーダーボードにコンテキスト データを追加する](/services/playfab/community/leaderboards/metadata-leaderboards)
* [Playstream を使用したリーダーボード](/services/playfab/community/leaderboards/leaderboards-with-playstream-and-telemetry)
* [API リファレンス](/services/playfab/community/leaderboards/api-reference)


## Related topics

- [PlayStream および Telemetry を使用したリーダーボード](/ja-jp/services/playfab/community/leaderboards/leaderboards-with-playstream-and-telemetry.md)
- [手動ティア リーダーボード](/ja-jp/services/playfab/community/leaderboards/manual-tiers.md)
- [イベントベース リーダーボードのサンプル コード](/ja-jp/services/xbox-services/player-data/stats-leaderboards/event-based/how-to/live-leaderboards-eb-howto.md)
- [タイトル管理型リーダーボードの取得](/ja-jp/services/xbox-services/player-data/stats-leaderboards/title-managed/how-to/live-getting-tm-leaderboard.md)
- [統計によってプレイヤーをランキング付けする](/ja-jp/services/playfab/community/leaderboards/leaderboards-linked-to-stats.md)
