Header Ads

Creating simple Android game with Google Play Game Services inside

Today I gonna present you a quick tutorial of creating a very simple game which uses Google Play Game Services – achievements and leaderboards. User will be able to log in, play a game, and save they score to the leaderboard. Let’s make… a multiplication trainer (you can find working example on Google Play, and as always, sources onGitHub)!
Google Play Game services game

Scenario

Well, multiplication trainer should check your knowledge of the multiplication table. But how we add a competition here? Let’s add a timer and a user who solve more equations per a minute than others will be at the top of leaderboard. Also, we will add achievements badges for 10, 20, 30, 40 and 50 (omg you’re a monster o_O!) equations per a minute.

Google Play Game Services overview

Google Play Game Services is a part of Google Play Services library, and offers Android developers (and not only) a set of cool services like achievementsleaderboardsquests, which are ready to use and there is no need to build and support own service – you just connect and use!

Setting up Google Play Services

To connect Google Play Services you should add specific dependency to your project. You can find full description here, and I’ll just show you a snippets for Android Studio and Gradle:
apply plugin: 'com.android.application'
...

dependencies {
    compile 'com.android.support:appcompat-v7:21.0.3'
    compile 'com.google.android.gms:play-services:7.0.0'
}
Add following lines to your manifest file:
<meta-data android:name="com.google.android.gms.version"
           android:value="@integer/google_play_services_version" />

Creating our game

Google has several example applications for Play Game services, and this example is based on TypeANumber one. These examples use a handy library called BaseGameUtils, let’s use it too (UPDATE: they don’t use it anymore the way described here):
  • Clone examples repo
  • Copy libraries/BaseGameUtils folder to the your project’s libs folder
  • Add include to settings.gradle:
    include ':libs:BaseGameUtils'
  • Add dependency to app/build.gradle:
    dependencies {
        ...
        compile project(':libs:BaseGameUtils')
    }
Now, let’s create our activity and extend it fromcom.google.example.games.basegameutils.BaseGameActivity for the sake of simplicity:
public class MainActivity extends BaseGameActivity{
...
}
Let’s declare custom API clients – CLIENT_GAMES and CLIENT_PLUS (to be able to log in users via Google+):
@Override
protected void onCreate(Bundle savedInstanceState) {
 setRequestedClients(CLIENT_GAMES | CLIENT_PLUS);
 getGameHelper();
 mHelper.setConnectOnStart(false);
 mHelper.setPlusApiOptions(PlusOptions.builder().build());

        super.onCreate(savedInstanceState);
        ...
We do this way to be able to set desired clients.
At first we have to log in user, it can be done with handy method fromBaseGameActivity:
beginUserInitiatedSignIn();
I use this method on the activity’s startup if user were already logged in (I save logged state to the preferences) and when user explicitly clicks on navigation drawer’s “Log in” item.
In depend on login result, these callbacks will be fired:
@Override
public void onSignInFailed() {
}

@Override
public void onSignInSucceeded() {
}
If login succeeded, we can get user’s name and profile picture:
Player p = Games.Players.getCurrentPlayer(getApiClient());
String displayName = p.getDisplayName();

Uri icon = p.getIconImageUri();
if (icon != null) {
 ImageManager im = ImageManager.create(getApplicationContext());
 mOnProfileImageLoadedlistener = new OnProfileImageLoadedListener();
 im.loadImage(mOnProfileImageLoadedlistener, icon);
}

private class OnProfileImageLoadedListener implements
   ImageManager.OnImageLoadedListener {
 @Override
 public void onImageLoaded(Uri uri, Drawable drawable,
    boolean isRequestedDrawable) {
                        // Profile picture is in the drawable argument
  }
 }
To check whether user is logged in or not you can use following method:
isSignedIn();
So, let’s imagine user played a game and now wants to save score stored inmSolvedCount:
private void doSaveScore() {
 Games.Leaderboards.submitScore(getApiClient(),
  getString(R.string.leaderboard_top_users), mSolvedCount);

 // Unlock the achievements
 if (mSolvedCount >= 10) {
  Games.Achievements.unlock(getApiClient(),
   getString(R.string.achievement_10_epm));
 } 
 if (mSolvedCount >= 20) {
  Games.Achievements.unlock(getApiClient(),
   getString(R.string.achievement_20_epm));
 }
 if (mSolvedCount >= 30) {
  Games.Achievements.unlock(getApiClient(),
   getString(R.string.achievement_30_epm));
 }
 if (mSolvedCount >= 40) {
  Games.Achievements.unlock(getApiClient(),
   getString(R.string.achievement_40_epm));
 } 
 if (mSolvedCount >= 50) {
  Games.Achievements.unlock(getApiClient(),
   getString(R.string.achievement_50_epm));
 }

 // Open leaderboard
 showLeaderboard();
}
Note the string R.string.leaderboard_top_users – this is the your game’s leaderboard ID on Google Play server, we’ll get it a bit later. For now you should create/res/values/games-ids.xml file and set these resources with arbitrary values to avoid errors.
Also you should add app_id resource to that file and reference it in the manifest this way:
<meta-data android:name="com.google.android.gms.games.APP_ID"
            android:value="@string/app_id" />
Also note how we unlocked achievements depending on the score, and there are also ID strings like R.string.achievement_10_epm – they identify achievements on Google Play server, and again we’ll get them later.
Now we want to display leaderboard for user to see his place in the overall rating:
startActivityForResult(Games.Leaderboards.getLeaderboardIntent(
 getApiClient(), getString(R.string.leaderboard_top_users)),
     RC_SHOWLEADERBOARD);
That’s all for basic things, please explore source code for details.

Setting up Google Play Game console

Now it’s time to set up our game in the Google Play Game console. I’ll illustrate this process with screenshots, and you can find more detailed explanation here.
Please note, that you have to build your APK, sign it with production certificate and upload it to the Google Play developer console before.
Go to the Google Play developer console and select Game services item on the left. Next, click on “+ Add new game”:
Google Play Game services game 1
Select I don’t use any Google APIs in my game yet and enter your game’s info:
Google Play Game services game 2
Then select Linked apps to the left. An then click on the Android one:
Google Play Game services game 3
Select your already uploaded app from the Package name list and confirm:
Google Play Game services game 4
Next you have to authorise your app so it will be able to make requests to the Google APIs. Google APIs uses OAuth 2.0 to authorize requests, so you will generate OAuth Client Id using your app’s production certificate. Note, that a new Google project will be automatically created and you can find it on the Google Developers Console.
Then click on Authorise your app now:
Google Play Game services game 5
Next fill in your game’s branding information:
Google Play Game services game 6
And then you should fill in your app’s package name and production certificate’s fingerprint:
Google Play Game services game 7
To get your certificate’s fingerprint you need to do following:
keytool -exportcert \
-alias <your-key-name> \
-keystore <path-to-production-keystore> \
-list -v
Now remember your application’s ID:
Google Play Game services game 8
Now it’s time to create our achievements (you should prepare icons for them). Click on the Achievements on the left, and then on Add new achievement:
Google Play Game services game 9
Fill in name, description and select icon, and select how much points you will give for this achievement:
Google Play Game services game 10
This is how your achievements will look like:
Google Play Game services game 11
Now go to the Leaderboards and click on Add new leaderboard button, and fill in needed fields:
Google Play Game services game 12
After creating your leaderboard, click on Get resources link below the list:
Google Play Game services game 13
You will get generated content for the game-ids.xml file which contains IDs for your application, achievements and leaderboard (remember R.string.achievement_10_epm and others we used earlier?). You should copy the content, create /res/values/games-ids.xml file and paste it there.
Now build your game APK once more and upload to the Google Play.
Note that you should publish your game before people world wide can play your game (don’t confuse with publishing your APK). You can test your game in unpublished state yourself, and if you have testers, you should whitelist them on Testing page.
When your game is carefully tested, publish it:
Google Play Game services game 15
Enjoy!

No comments:

Powered by Blogger.