Making an Android game with LibGDX part #3 – Google Play Services setup

Hi everyone!

We made it to part #3! Yeah! You can find the previous parts here:

Part #1 – Introduction and setup

Part #2 – Game Code

Now that we have a minimal game with a score, we can start implementing the Google Play Service – Sign in, Leaderboards and Achievements.  Let’s go!

Fire up Android Studio and load our part #2 project.

Open the project’s build.gradle(top level) and add the following rules and dependencies:

androidTutorial [:Volumes:BACKUP:Android_Projects:androidTutorial] - androidTutorial 2019-02-28 21-23-23.png

Inside buildscript{} add the following:

classpath 'com.google.gms:google-services:4.2.0'

Inside project(“:android”) add these implemantations:

implementation "com.google.android.gms:play-services-games:16.0.0"
implementation "com.google.android.gms:play-services-auth:16.0.1"

Now open Module:android build.gradle

androidTutorial [:Volumes:BACKUP:Android_Projects:androidTutorial] - android 2019-02-28 21-23-08.png

and at the end add:

apply plugin: 'com.google.gms.google-services'

Hit Sync Now and everything should go well.

Now we have made all the required libraries available to our project, let’s start setting up Google Play services from the Google Play console.

Google Play Service

Before we start writing some code, we need to create a new application in Goole Play Console so we can setup the client ID. Client ID is the link between your game/app and almost all the Google Play services.

From inside Google Play Console create a new application.

All applications - Google Play Console 2019-03-03 13-12-39.png

Name your app as you like. Now that we have a blank app, click Game Services from the left side menu:

All applications - Google Play Console 2019-03-03 13-17-17.png

and add a new game:

Game services - Google Play Console 2019-03-03 13-19-03.png

From the popup dialog, choose ” I don’t use any Google APIs in my game yet” and fill in the required fields and click Continue.

Game services - Google Play Console 2019-03-03 13-20-14.png

Now we need to create a linked application.

Linked Application

From the Linked Apps menu, choose Android.

Linked apps - Libgdx Demo tutorial - Google Play Console 2019-03-08 19-47-05.jpg

For the next step just fill your game’s package name and optionally enable Anti-piracy, a nice to have feature.

Linked apps - Libgdx Demo tutorial - Google Play Console 2019-03-08 19-50-56.jpg

Click Save and Continue and from Step 2 click Authorize your app now.

A new dialog will pop up with the signing certificate fingerprint input (SHA1).

Linked apps - Libgdx Demo tutorial - Google Play Console 2019-03-08 20-40-22.png

Here  we must generate a SHA1 from our keystore file, the file used to sign our APK just before we upload it to Google Play Store for review and release. Since we first need to test our app, we are going to use the debug keystore that came with Android Studio.

Open the terminal(MacOS and Linux) or the command prompt(Windows) and run the keytool command to get the SHA1:

keytool -list -keystore ~/.android/debug.keystore

The default password is android.

The command will output the SHA1 that we need to paste in the last dialog. Paste it and click Confirm. If the linking is successful, you will be presented with your application ID.

Android Studio Client ID

Following these steps will link our game with the Google Play Services. Note that, in this stage we are still testing our game, thus we are using the debug keystore. When we will be ready to release it, we need to create a new linked app inside the Play Console with a new SHA1, generated from our production keystore.

The application ID must be pasted inside the strings.xml file, but we can create a separate xml file for all the IDs that we are going to use(leaderboards, achievements etc).

Create a new resource file and name it ids.xml:

androidTutorial [:Volumes:BACKUP:Android_Projects:androidTutorial] - ...:core:src:com:tut:mygame:MyGdxGame.java [core] 2019-03-09 11-27-32.jpg

Now paste the following lines:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <!-- app_id -->
    <string name="app_id">666777888999</string>

    <!-- package_name -->
    <string name="package_name">com.tut.mygame</string>
    
</resources>

Next we need to modify our AndroidManifest.xml and include the application ID. Since we are here, we can add some options regarding OpenGL and Internet Access. The xml file should look like this:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.tut.mygame" >

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />


    <!-- Tell the system this app requires OpenGL ES 2.0. -->
    <uses-feature android:glEsVersion="0x00020000" android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:isGame="true"
        android:appCategory="game"
        android:label="@string/app_name"
        android:theme="@style/GdxTheme"
        tools:ignore="GoogleAppIndexingWarning"
        android:keepScreenOn="true"
        tools:targetApi="o">

        <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/app_id" />

        <activity
            android:name="com.tut.mygame.AndroidLauncher"
            android:label="@string/app_name" 
            android:screenOrientation="portrait"
            android:configChanges="keyboard|keyboardHidden|navigation|orientation|screenSize|screenLayout">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Unfortunately, the length of this part is too big to include the required Java code for the Google Play Service, which means until part #4! 😦 Sorry.

You can find the part #3 code here

Until next time!

Advertisements

Making an Android game with LibGDX part #2 – Game sample code

Hi everyone!

This is the 2nd post of my (eventually) multi-series tutorials on how to make and publish a game using Libgdx. Then previous posts are:

Part #1 – Introduction and setup

Before we move on with the implementation of Google Play services and Firebase analytics, we should have a simple game in our hand so I can show you how post scores to leaderboards, add achievements and other nice to have features.

Game logic

For the need of these tutorials, we are going to make a simple game. The main logic will be the following: On screen, there will be flashing random images and the player must touch them before they disappear. Simple:)

Fire up Android Studio and open our project(you can find it here on Github).

Open the MyGdxGame class inside the core->java folder:

androidTutorial [:Volumes:BACKUP:Android_Projects:androidTutorial] - ...:core:src:com:tut:mygame:MyGdxGame.java [core] 2019-02-17 23-08-06.png

This is the starting point of our game ( for the libgdx part). First we should edit it to look like this:

package com.tut.mygame;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

public class MyGdxGame extends Game  
                                implements ApplicationListener {
   private SpriteBatch batch;

   @Override
   public void create () {
      batch = new SpriteBatch();
      Assets.load();
   }

   @Override
   public void render () {

   }
   
   @Override
   public void dispose () {
      batch.dispose();
   }
}

As I mentioned earlier, MyGdxGame class serves as a starting point of our libgdx game. Inside the create() method we could define our SpriteBatch and reuse it again, saving resources. Also, when we are finished initialising assets and other resources, we are ready to launch our first screen a game screen

But before we do this, we should create another class, where we can load our assets separately. This is not mandatory but it’s good practise and you produce clean code.

Click File->New->Java Class

Create New Class 2019-02-18 20-42-31.png

Now we need some graphics. Copy a sample png image inside Android/assets folder. I named it tux.png.

androidTutorial [:Volumes:BACKUP:Android_Projects:androidTutorial] - ...:core:src:com:tut:mygame:Assets.java [core] 2019-02-18 20-50-38.png

Tux will be our main object that will interact with the user.

Back in Assets Class let’s load it.

package com.tut.mygame;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;

public class Assets {
    public static Texture tuxImage;

    static void load() {
        tuxImage = new Texture(Gdx.files.internal("tux.png"));
    }

    static void dispose() {
        tuxImage.dispose();
    }
}

Here we have the method load() that will be called once and all of our assets will be available to all classes.

Back in our MyGdxGame Class and inside the create() method add the following line and all of our assets will be loaded.

Assets.load();

By now let’s edit the MyGdxGame class with some game logic:

package com.tut.mygame;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.RandomXS128;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector3;
import java.util.Random;

public class MyGdxGame extends Game  implements ApplicationListener {
   private SpriteBatch batch;
   private OrthographicCamera camera;
   private Rectangle tuxRect;
   private Random rnd;
   private boolean showTux=true;
   private Long startTime;
   private int score;
   private boolean endGame;

   @Override
   public void create () {
     Gdx.graphics.setContinuousRendering(false);
     Gdx.graphics.requestRendering();
     Assets.load();
     camera = new OrthographicCamera();
     camera.setToOrtho(false, 480, 640);
     tuxRect = new Rectangle();
     tuxRect.setWidth(Assets.tuxImage.getWidth());
     tuxRect.setHeight(Assets.tuxImage.getHeight());
     tuxRect.x = 240f; 
     tuxRect.y = 60f;
     batch = new SpriteBatch();
     rnd = new RandomXS128();
     rnd.setSeed(System.currentTimeMillis() / 1000L);
     startTime = System.currentTimeMillis()/1000L;
  }

    public void update() {
      if ((System.currentTimeMillis()/1000L) - startTime <10) {
        if (showTux) {
          tuxRect.x = rnd.nextInt((int) (480 - tuxRect.width));
          tuxRect.y = rnd.nextInt((int) (640 - tuxRect.height));
          showTux = false;
          Gdx.graphics.requestRendering();
        }
 
     if (Gdx.input.isTouched()) {
       Vector3 touchPos = new Vector3();
       touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
       camera.unproject(touchPos);
       if (touchPos.x >= tuxRect.x && touchPos.x <= tuxRect.x + tuxRect.width) {
         showTux = true;
         score++;
       }
     }
          
     } else {
       System.out.println("END GAME"+score);
       endGame = true;
     }
   }

   @Override
   public void render (){
     update();
     Gdx.gl.glClearColor(66/255f,159/255f, 70/255f, 1);
     Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
     camera.update();
     batch.setProjectionMatrix(camera.combined);
     batch.begin();
     if (!endGame) {
      batch.draw(Assets.tuxImage, tuxRect.x, tuxRect.y);
     }
     batch.end();
   }
   
   @Override
   public void dispose () {
      batch.dispose();
      Assets.dispose();
   }
}

Our game is simple. The player must touch the penguin as many times as he can in 10 seconds. Simple!

When 10 seconds are passed, we get a score value that we need in order to show how to submit to Google Play.

This concludes part #2 of our tutorial.

You can find the code for this part at github.

Until next time!

Making an Android game with LibGDX part #1 – Introduction and Setup

Recently I converted / rewritten an old android game I’ve made in the past and decided(after a lot of researching) to use LibGDX. If you are not familiar with LibGDX, then go ahead to the official website and see what is all about.

If you want the TL;DR version, then LibGDX is a game development framework for 2D(mainly) and 3D games. It’s open source, fast and it has a fast and easy learning curve.

Libgdx is not a full game engine like CoronaSDK (my number 2 in my list) or Unity. Also, despite the fact that the last stable update was some time ago, LibGDX is very fun to use and very rewarding.

This series of tutorials will guide you from the setup of your first libgdx game to the publishing process required to take in order your game hits the market and get installed in thousands of Android devices!

The series will eventually cover:

  • Creating a new project with Libgdx(this post)
  • Basic framework concepts(views, camera, input events)
  • Implementing Google Ads, Google Play services, Firebase analytics etc
  • Google play console setup (Leaderboards and Achievements)
  • Testing
  • Publishing
  • Updating your app with new features

All tutorials are written and developed on iMac using Android Studio 3.3.1 and Libgdx 1.9.9.

Let’s start!

Android Studio and Libgdx initial setup

Before we begin, make sure you have Android Studio installed. Then download the libgdx setup tool: https://libgdx.badlogicgames.com/nightlies/dist/gdx-setup.jar .

With the help of this tool, you’ll be able to generated a ready-to-import Android Studio project with libgdx included. Run the setup tool and the following window will appear:

LibGDX Project Generator 2019-02-14 17-11-05.png

Name is your game’s name.

Package is the unique package for your Android game.

Game class is the main class of your game. We will use this as the starting point of our game.

Destination folder (self-explanatory)

Android SDK is the location of the Android SDK on your computer. You can find it by clicking Configure->SDK Manager from the Android Studio welcome screen.

Welcome to Android Studio 2019-02-14 17-08-45.png

Preferences for New Projects 2019-02-14 17-06-11.png

Back to the Libgdx setup tool, check only the Android option in Sub Projects, the Tools and Freetype in Extensions and then click Show Third Party Extensions and check the libgdx-utils and gdx-dialogs options.

All the above options(except the Android of course) and not mandatory, but it’s nice to have from the beginning. We will discuss later what every extension does.

When you are ready, click Generate and if all goes well, you see the instructions to import your new project in Android Studio.

LibGDX Project Generator 2019-02-14 17-28-46.png

Back at Android Studio, click Import and select your project.

Welcome to Android Studio 2019-02-14 17-34-03.png

During the import and the initial setup, there is a chance Android Studio will ask you to update your project with the latest Gradle plugin. Choose Update.

Android Gradle Plugin Update Recommended 2019-02-14 17-38-58.png

When syncing is finished, you should not have any errors in the Build Panel. A warning may appear telling you to update your project’s build.gradle.

androidTutorial [:Volumes:BACKUP:Android_Projects:androidTutorial] - androidTutorial 2019-02-14 17-43-38.png

You can go ahead and change the ‘compile’ option with ‘implementation’ and ‘api’, but for now it’s ok to skip this step.

After editing our gradle file, here how it looks:

androidTutorial [:Volumes:BACKUP:Android_Projects:androidTutorial] - androidTutorial 2019-02-15 09-43-48.png

Now let’s try our new game and make sure everything is working.

Android Emulator - Nexus_5_API_28:5554 2019-02-15 16-41-56.png

It works! Great.

This is the end of part 1, I hope you like it.

You can find the source code for the project here: https://github.com/thiodordelis/libgdx-android-tutorial

Enjoy!