‹ Google Play Games Services Doc Home

Google Play Games Services Integration Guide

For the Javascript version of cocos2d-x v3.x - (all other versions)

SDK Version

Integration

Open a terminal and use the following command to install the SDKBOX Google Play Games Services plugin. Make sure you setup the SDKBOX installer correctly.

$ sdkbox import gpg

Warning: Account creation within iOS is no longer supported, please read this blog post for details

After Installation

Android

Update AndroidManifest.xml

Add this meta-data tag to your AndroidManifest.xml

<meta-data android:name="com.google.android.gms.games.APP_ID"
    android:value="@string/google_app_id" />

Update string.xml

Add this entry to proj.android/res/values/string.xml

<string name="google_app_id">777734739048</string>

Replace google_app_id value with your own App Id.

iOS

Set a rootview controller for GPG:

Update proj.ios_mac/ios/RootViewController.h Add this:

#import <GoogleSignIn/GoogleSignIn.h>

// Change RootViewController class definition to:
@interface RootViewController : UIViewController<GIDSignInUIDelegate>

Set Google Play signin listeners

Update proj.ios_mac/ios/AppController.mm

  1. Add this method:
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options {
    return [[GIDSignIn sharedInstance] handleURL:url
                               sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey]
                                      annotation:options[UIApplicationOpenURLOptionsAnnotationKey]];
}
  1. In this method:
(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

add a call to (before return YES):

    // _viewController could also be named
    //  viewController, depending of the project type.
    [GIDSignIn sharedInstance].uiDelegate = _viewController;

Add URL types

Add the following URL types under your project > Info > URL Types

Further info

For more information check out the official documentation

Important Notice

Please make sure the following settings in your project to make the plugin work well.

Disable App Transport Security

Adding the following entry to the info.plist file:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

It should look like this:

Disable Bitcode support

You have to turn off Bitcode support. If you don't, cocos2d-x will fail to build.

Set your game requires full screen

If your game doesn't support all screen orientations, you will need to check Requires full screen in Xcode. If you do not, your app will fail Apple's submission process.

Whitelist canOpenURL function

This setting depends on what plugins are in your project. You may need to add the required entry to the info.plist, under LSApplicationQueriesSchemes.

Usage

Pre-requisites

Your must create your app on Google Play Developer console and all the services must be explicitly enabled and configured in the console.

Note: Google Play Games Services will use your release keystore by default, if you want to test your game in debug settings, please link an additional app with debug keystore

Register Javascript Functions

You need to register all the Google Play Games JS functions with cocos2d-x before using them.

To do this: * Modify ./frameworks/runtime-src/Classes/AppDelegate.cpp to include the following headers:

#include "PluginGPGJS.hpp"
#include "PluginGPGJSHelper.h"
    sc->addRegisterCallback(register_all_PluginGPGJS);
    sc->addRegisterCallback(register_all_PluginGPGJS_helper);

Initialize Google Play Games

Google Play initialization is thorughout a gpg.Builder object. This is a valid copy-and-paste example for authenticating into the library:


new gpg.GameServices.Builder()
            .SetOnAuthActionStarted( function( result ) {
                // Auth started callback
            })
            .SetOnAuthActionFinished( function( result ) {
                // Auth finished callback
            })
            .SetLogging( gpg.LogLevel.INFO )    // Set Logging level
            .EnableSnapshots()                  // Enable Snapshot (Saved Game) functionailty
            .Create( function( game_services ) {
                // 8
            } );

Let's dive into this process step by step.

Initialization Process breakdown

Create a gpg.PlatformConfiguration object. The client id will be specific for your application, and only needed on iOS.

The next step is to create a GameServices object, it will provide the access to all Google Play Game Services.

Authorization Callback

There are two callback for GPG authentication AuthActionStarted and AuthActionFinished

Auth started

//result.AuthOperation indicates if user wants sign in or sign out
.SetOnAuthActionStarted(
    function( result ) {
        cc.log('on auth action started: ' + result.AuthOperation);
    })

Auth finished

.SetOnAuthActionFinished(
    function( result ) {
        cc.log('on auth action finished: ' + result.AuthOperation + ' ' + result.AuthStatus);
    })

Set Logging Level

Set Logging level is an optional step, but worth mentioning since this is the only place where GPG logging capabilities can be controlled from.

Enable Saved Game

If your game expects to save games on the cloud, this is step would be mandatory and you have to specify it during initialization.

Step 8

Until this steps, all previous code is authentication set up. This Create call is the actual executable code to be authenticated, notified appropriately and again access to the GPG objects. GPG interation will happen by means of a gpg.GameServices object. This object will eventually been passed to the Create method's callback if everything went ok.

Authorization

All Google Play Game services require user login. So after GPG has been initialized you should attempt to log user in with following API

    game_services.StartAuthorizationUI();

Achievements

Achievements can be a great way to increase your users' engagement within your game. You can implement achievements in your game to encourage players to experiment with features they might not normally use, or to approach your game with entirely different play styles. Achievements can also be a fun way for players to compare their progress with each other and engage in light-hearted competition.

For example, you could unlock gpg.GameServices.Achievements.Unlock, increment gpg.GameServices.Achievements.Increment or reveal an achievement gpg.GameServices.Achievements.Reveal.

For more information refer to: Achievements documentation

Leaderboards

Leaderboards can be a fun way to drive competition among your players, both for your most hardcore fans (who will be fighting for the top spot in a public leaderboard) and for your more casual players (who will be interested in comparing their progress to their friends').

For example, it gives access to metadata about a leaderboard gpg.GameServices.Leaderboards.Fetch, pages with user's scores gpg.GameServices.Leaderboards.FetchScorePage, etc.

For more information refer to: Leaderboards documentation

Saved Games

The Saved Games service gives you a convenient way to save your players' game progression to Google's servers. Your game can retrieve the saved game data to allow returning players to continue a game at their last save point from any device. The Saved Games service makes it possible to synchronize a player's game data across multiple devices.

For more intormation refer to: Saved Games documentation

Real-time multiplayer

Your game can use the real-time multiplayer API in Google Play games services to connect multiple players together in a single game session and transfer data messages between connected players. Using the real-time multiplayer API can help to simplify your game development effort because the API handles the following tasks on your behalf:

For more information refer to: Real-time Multiplayer documentation

Turn-based multiplayer

In a turn-based multiplayer game, a single shared state is passed between multiple players, and only one player has permission to modify the shared state at a time. Players take turns asynchronously according to an order of play determined by the game. Your game can use the turn-based multiplayer API provided by Google Play games services to manage the following tasks:

For more information refer to: Turn-based Multiplayer documentation

Player Statistics

Gets and sets various player-related data. For example, gives information about the current logged-in player gpg.GameServices.Players.FetchSelf, or about any player identified by an id gpg.GameServices.Players.Fetch. Also, player stats can be obtained with interesting information such as a player's average session length, number of days since last played or the number of purchased he's done on the game. For more information please take a look at Player Stats documentation

Events and Quests

The Google Play Games events service allows you to collect cumulative data generated by your players during gameplay and store them in Google's servers for game analytics. You can flexibly define what player data your game should collect; this might include metrics such as how often:

You can use the events data as feedback on how to improve your game. For example, you can adjust the difficulty level of certain levels in your game that players are finding too hard to complete.

For example you could accept a Quest gpg.GameServices.Quests.Accept or claim milestones on a given quest gpg.GameServices.Quests.AcceptMilestone.

For more information refer to: Events and Quests documentation

Nearby Connections

Nearby Connections enables local multiplayer and screen casting for your game. For more information please take a look at Nearby documentation

API Reference

All the javascript code is already annotated and will populate intellisense from all the major Javascript IDEs like IntelliJ, Webstorm, Visual Studio Code, etc.

Online API Reference for Google Play Games

Manual Integration

If the SDKBOX Installer fails to complete successfully, it is possible to integrate SDKBOX manually. If the installer complete successfully, please do not complete anymore of this document. It is not necessary.

These steps are listed last in this document on purpose as they are seldom needed. If you find yourself using these steps, please, after completing, double back and re-read the steps above for other integration items.

Manual Integration For iOS

Drag and drop the following frameworks from the plugins/ios folder of theGooglePlay bundle into your Xcode project, check Copy items if needed when adding frameworks:

sdkbox.framework

PluginGPG.framework

GoogleAppUtilities.framework

GoogleAuthUtilities.framework

GoogleNetworkingUtilities.framework

GoogleOpenSource.framework

GooglePlus.bundle

GooglePlus.framework

GoogleSignIn.bundle

GoogleSignIn.framework

GoogleSymbolUtilities.framework

GoogleUtilities.framework

gpg.bundle

gpg.framework

The above frameworks depend upon other frameworks. You also need to add the following system frameworks, if you don't already have them:

AddressBook.framework

AssetsLibrary.framework

CoreData.framework

CoreLocation.framework

CoreMotion.framework

CoreTelephony.framework

CoreText.framework

Foundation.framework

MediaPlayer.framework

QuartzCore.framework

SafariServices

Security.framework

StoreKit

Security.framework

SystemConfiguration.framework

libc++.dylib

libz.dylib

Add a linker flag, if your setup requires it, to: Target -> Build Settings -> Linking -> Other Linker Flags:

-ObjC

Code changes

Set a rootview controller for GPG:

Update proj.ios_mac/ios/RootViewController.h Add this:

#import <GoogleSignIn/GoogleSignIn.h>

// Change RootViewController class definition to:
@interface RootViewController : UIViewController<GIDSignInUIDelegate>

Set Google Play signin listeners

Update proj.ios_mac/ios/AppController.mm

  1. Add this method:
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options {
    return [[GIDSignIn sharedInstance] handleURL:url
                               sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey]
                                      annotation:options[UIApplicationOpenURLOptionsAnnotationKey]];
}
  1. In this method:
(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

add a call to (before return YES):

    // _viewController could also be named
    //  viewController, depending of the project type.
    [GIDSignIn sharedInstance].uiDelegate = _viewController;

Add URL types

Add the following URL types under your project > Info > URL Types

Further info

For more information check out the official documentation

Manual Integration For Android

SDKBOX supports three different kinds of Android projects command-line, eclipse and Android Studio.

Copy Files

Copy the following jar files from plugin/android/libs folder of this bundle into your project's /libs folder.

Plugingpg.jar

sdkbox.jar

Copy jni libs

Copy and overwrite all the folders from plugin/android/jni to your <project_root>/jni/ directory.

Edit AndroidManifest.xml

Add following meta-data tags:

<meta-data android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" />
<meta-data android:name="com.google.android.gms.games.APP_ID"
    android:value="@string/google_app_id" />

Make sure to add an entry to the file res/values/string.xml of the form: <string name="google_app_id">777734739048</string> Change that value for your own generated play games App Id.

Edit Android.mk

Edit <project_root>/jni/Android.mk to:

Install in a folder named gpg inside your proj.android\jni directory

Add this to your android.mk file

Add include path

LOCAL_C_INCLUDES += ./gpg/include/

Add static libraries

Add additional requirements to LOCAL_WHOLE_STATIC_LIBRARIES:

LOCAL_WHOLE_STATIC_LIBRARIES += gpg-1
LOCAL_WHOLE_STATIC_LIBRARIES += PluginGPG
LOCAL_WHOLE_STATIC_LIBRARIES += sdkbox

Add a call to:

$(call import-add-path,$(LOCAL_PATH))

before any import-module statements.

Add additional import-module statements at the end:

$(call import-module, ./gpg)
$(call import-module, ./sdkbox)
$(call import-module, ./plugingpg)

Note: It is important to make sure these statements are above the existing $(call import-module,./prebuilt-mk) statement, if you are using the pre-built libraries.

Modify Application.mk (Cocos2d-x v3.0 to v3.2 only)

Edit <project_root>/jni/Application.mk to make sure APP_STL is defined correctly. If Application.mk contains APP_STL := c++_static, it should be changed to:

APP_STL := gnustl_static

Modify Cocos2dxActivity.java

Note: When using Cocos2d-x from source, different versions have Cocos2dxActivity.java in a different location. One way to find the location is to look in proj.android/project.properties. Example: android.library.reference.1=../../cocos2d-x/cocos/platform/android/java

In this case, Cocos2dxActivity.java should be located at:

../../cocos2d-x/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java
import android.content.Intent;
import com.sdkbox.plugin.SDKBox;
onLoadNativeLibraries();
SDKBox.init(this);
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
          if(!SDKBox.onActivityResult(requestCode, resultCode, data)) {
            super.onActivityResult(requestCode, resultCode, data);
          }
    }
    @Override
    protected void onStart() {
          super.onStart();
          SDKBox.onStart();
    }
    @Override
    protected void onStop() {
          super.onStop();
          SDKBox.onStop();
    }
    @Override
    protected void onResume() {
          super.onResume();
          SDKBox.onResume();
    }
    @Override
    protected void onPause() {
          super.onPause();
          SDKBox.onPause();
    }
    @Override
    public void onBackPressed() {
          if(!SDKBox.onBackPressed()) {
            super.onBackPressed();
          }
    }

Manual Integration for Google Play Services SDK (dependent library only)

Suggestion

Please try the SDKBOX installer first. It will do all the following step for you automatically.

$ sdkbox import googleplayservices

Modify project.properties

An Android Library Reference for Google Play Services is required. The path will be different depending upon your setup. Also, this is an additional download that does not come as part of a standard install. To install use the sdk installer and choose extras->google play services. Here is an example of what this line could look like:

android.library.reference.1=
../android/sdk.latest/extras/google/google_play_services/libproject/
google-play-services_lib

Note: if you already have an android.library.reference.1 you can add another by incrementing the number as android.library.reference.2, etc.

Integration manually

We make a lite version of Google Play Services, the project repo is https://github.com/darkdukey/Google-Play-Service-Lite

Copy Files

Copy the gps folder from plugin folder of this bundle into your project's /libs folder.

Modify files for Eclipse

  1. Modify project.properties
# For source project
android.library.reference.2=../cocos2d/cocos/platform/android/java/libs/gps/

# Or
# For framework project
android.library.reference.1=libs/gps/

Modify files for Android Studio

1. Modify cocos2d/cocos/platform/android/libcocos2dx/build.gradle
 dependencies {
+    compile project(':gps')
     compile fileTree(dir: '../java/libs', include: ['*.jar'])
 }
2. Modify proj.android-studio/app/project.properties
 # Project target.
 target=android-14
+android.library.reference.1=../cocos2d/cocos/platform/android/java/libs/gps/
3. Modify proj.android-studio/settings.gradle
 project(':libcocos2dx').projectDir = new File(settingsDir, '../cocos2d/cocos/platform/android/libcocos2dx')
 include ':your_project_name'
 project(':your_project_name').projectDir = new File(settingsDir, 'app')
+
+include ':gps'
+project(':gps').projectDir = new File(settingsDir, '../cocos2d/cocos/platform/android/java/libs/gps')

Proguard (optional)

proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
# cocos2d-x
-keep public class org.cocos2dx.** { *; }
-dontwarn org.cocos2dx.**
-keep public class com.chukong.** { *; }
-dontwarn com.chukong.**

# google play service
-keep class com.google.android.gms.** { *; }
-dontwarn com.google.android.gms.**

-keep class * extends java.util.ListResourceBundle {
    protected Object[][] getContents();
}

-keep public class com.google.android.gms.common.internal.safeparcel.SafeParcelable {
    public static final *** NULL;
}

-keepnames @com.google.android.gms.common.annotation.KeepName class *
-keepclassmembernames class * {
    @com.google.android.gms.common.annotation.KeepName *;
}

-keepnames class * implements android.os.Parcelable {
    public static final ** CREATOR;
}

#sdkbox
-keep class com.sdkbox.** { *; }
-dontwarn com.sdkbox.**

Note: Proguard only works with Release builds (i.e cocos run -m release) debug builds do not invoke Proguard rules.