页首横幅

本指南介绍了如何使用 Play 游戏服务 c++ SDK 排行榜 API 来创建直观的排行榜、记录玩家得分,以及将玩家的最新得分与他们在之前游戏会话中的得分进行比较。您可以在 LeaderboardsClient 中找到这些 API。

准备工作

请阅读排行榜游戏概念(如果您尚未执行此操作)。

开始使用排行榜 API 进行编码之前,请执行以下操作:

获取排行榜客户端

如需开始使用排行榜 API,您的游戏必须先获取一个 LeaderboardsClient 对象。 为此,您可以调用 PgsLeaderboardsClient_create() 方法并传入 activity。

更新玩家得分

当玩家得分发生变化时(例如,玩家完成 游戏时),游戏可以在排行榜上更新玩家得分,具体做法是调用 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。此函数需要客户端句柄、activity、排行榜 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);

此函数会显示界面。activity 对象提供用于显示界面的上下文。