> ## 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](/zh-TW/services/playfab/live-service-management/service-gateway/automation/cloudscript-af)。
這種方法很強大，因為它可讓您建立自訂的伺服器端邏輯，而不需要更新用戶端。

在 Azure 函式中定義與排行榜相關的邏輯後，您的用戶端就可以叫用該函式來執行程式碼。如果之後需要變更，您可以獨立更新 Azure 函式，視更新的複雜度而定，通常不需要修改用戶端。

## 必要條件

若要依照本教學課程操作，您需要：

* PlayFab 帳戶。如果您沒有帳戶，可以在[這裡](https://developer.playfab.com/)建立。
* Azure 訂用帳戶。如果您沒有訂用帳戶，可以在[這裡](https://azure.microsoft.com/free/)建立。

如需如何建立 Azure 函式的詳細資訊，請參閱此指南。[使用 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`。
* 此函式由 HTTP 要求觸發，如 `[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")]` 屬性所示。這表示無需任何驗證，即可透過 HTTP GET 和 POST 方法存取此函式。
* 在函式中，我們設定 PlayFab 遊戲 ID 和開發人員秘密金鑰，以驗證我們對 PlayFab 服務的要求。您可以根據最適合您特定案例和安全性需求的方式，變更存取這些值的方法。
* 此函式會檢查要求中是否提供查詢參數 "leaderboardName"。
* 接著我們呼叫 `LoginAsTitleEntity` 方法，以遊戲實體身分進行驗證，這是建立排行榜定義所必需的。
* 最後，我們呼叫 `CreateLeaderboardDefinitionAsync` 方法，以提供的名稱建立排行榜定義。若要深入了解排行榜的建立，您可以參閱[建立基本排行榜](/zh-TW/services/playfab/community/leaderboards/create-basic-leaderboard)和[使用排行榜執行更多操作](/zh-TW/services/playfab/community/leaderboards/doing-more-with-leaderboards)。

RunAsync 方法是您 Azure 函式的進入點。從這裡，您可以定義並呼叫其他方法來建置您的自訂遊戲邏輯。如何處理錯誤或與多個 PlayFab 服務互動完全由您決定，讓您在實作上擁有完全的彈性。

此外，您可以設定自動化規則，根據特定事件觸發此 Azure 函式。如需詳細資訊，請參閱[這裡](/zh-TW/services/playfab/live-service-management/service-gateway/automation/cloudscript-af/quickstart)。

## 另請參閱

* [使用排行榜執行更多操作](/zh-TW/services/playfab/community/leaderboards/doing-more-with-leaderboards)。
* [建立基本排行榜](/zh-TW/services/playfab/community/leaderboards/create-basic-leaderboard)。
* [手動層級](/zh-TW/services/playfab/community/leaderboards/manual-tiers)。
* [限制](/zh-TW/services/playfab/community/leaderboards/limits-leaderboards)。
* [配額](/zh-TW/services/playfab/community/leaderboards/quota-leaderboards)。
* [季節性排行榜](/zh-TW/services/playfab/community/leaderboards/seasonal-leaderboards)。
* [依統計資料為玩家排名](/zh-TW/services/playfab/community/leaderboards/leaderboards-linked-to-stats)。
* [將內容相關資料新增至排行榜](/zh-TW/services/playfab/community/leaderboards/metadata-leaderboards)。
* [排行榜與 Playstream](/zh-TW/services/playfab/community/leaderboards/leaderboards-with-playstream-and-telemetry)。
* [API 參考](/zh-TW/services/playfab/community/leaderboards/api-reference)。


## Related topics

- [取得使用者角色的排行榜](/zh-TW/services/playfab/api-references/rest/server/characters/get-leaderboard-for-user-characters.md)
- [取得使用者周圍的排行榜](/zh-TW/services/playfab/api-references/rest/server/player-data-management/get-leaderboard-around-user.md)
- [排行榜](/zh-TW/build/steam-porting-guide/features/steam-leaderboards.md)
- [在 Partner Center 中設定排行榜](/zh-TW/publishing/game-publishing/how-to/data-platform-2013/how-to-configure-leaderboards-2013.md)
- [使用排行榜執行更多操作](/zh-TW/services/playfab/community/leaderboards/doing-more-with-leaderboards.md)
