排行榜

本指南說明如何使用 Play Games 服務 C++ SDK 排行榜 API,建立圖像排行榜、記錄玩家分數,並與前一個遊戲工作階段的玩家分數比較。這些 API 位於 LeaderboardsClient

事前準備

建議您先複習排行榜遊戲概念,這會對您很有幫助。

開始使用排行榜 API 編寫程式碼之前:

取得排行榜用戶端

遊戲必須先取得 LeaderboardsClient 物件,才能使用排行榜 API。要取得此物件,您可以呼叫 PgsLeaderboardsClient_create() 方法,然後在活動內傳遞。

更新玩家得分

當玩家分數有所變動 (例如玩家結束遊戲時),遊戲可以呼叫 PgsLeaderboardsClient_submitScoreImmediate,更新排行榜上的玩家分數。您需要傳遞排行榜 ID、原始分數值、選用的分數標記,以及回呼函式。

// Callback function to handle the result of submitting the score
void OnScoreSubmitted(PgsStatusCode status_code,
                      PgsScoreSubmissionData* score_submission_data,
                      void* user_data) {
  if (status_code == PGS_STATUS_SUCCESS) {
    // Score submitted successfully
    // You can inspect score_submission_data for details
    // Remember to release the data when done:
    PgsScoreSubmissionData_Release(score_submission_data);
  } else {
    // Handle error
  }
}

// Function to submit the score
void SubmitScore(PgsLeaderboardsClient* client, const char* leaderboard_id, int64_t score) {
  const char* score_tag = NULL; // Optional tag

  PgsLeaderboardsClient_submitScoreImmediate(
      client,
      leaderboard_id,
      score,
      score_tag,
      OnScoreSubmitted,
      NULL // user_data - optional context pointer
  );
}

// Example usage:
// Assuming 'my_leaderboard_id' is defined elsewhere, e.g., fetched from resources
// SubmitScore(leaderboards_client, my_leaderboard_id, 1337);

建議您在 C++ 程式碼中,將排行榜 ID 設為常數或資源。

顯示排行榜

如要顯示特定排行榜的預設排行榜使用者介面,請呼叫 PgsLeaderboardsClient_showLeaderboardUI。這項函式需要用戶端控制代碼、活動、排行榜 ID、時間範圍和集合,以及回呼。

// Callback function to handle the result of showing the UI
void OnShowLeaderboardUI(PgsStatusCode status_code, bool success, void* user_data) {
  if (status_code == PGS_STATUS_SUCCESS && success) {
    // UI was shown successfully
  } else {
    // Handle error or failure to show UI
  }
}

// Function to show a specific leaderboard UI
void ShowLeaderboard(PgsLeaderboardsClient* client, jobject activity, const char* leaderboard_id) {
  PgsLeaderboardsClient_showLeaderboardUI(
      client,
      activity,
      leaderboard_id,
      PGS_LEADERBOARD_TIME_SPAN_ALL_TIME, // Or PGS_LEADERBOARD_TIME_SPAN_DAILY, PGS_LEADERBOARD_TIME_SPAN_WEEKLY
      PGS_LEADERBOARD_COLLECTION_PUBLIC,  // Or PGS_LEADERBOARD_COLLECTION_FRIENDS
      OnShowLeaderboardUI,
      NULL // user_data - optional context pointer
  );
}

// Example usage:
// ShowLeaderboard(leaderboards_client, android_activity, my_leaderboard_id);

這個函式會顯示 UI。activity 物件提供顯示 UI 的背景資訊。