Please share...

  • Video courses

    All game programming videos just $19 - For a very limited time these three videos and thousands more are up to 90% off!

    Just enter coupon code NEWU19 in cart/checkout

Unity Pro Development A to Z – Build 10 Android/iOS Games

The Complete Android & Java Developer Course – Build 21 Apps

The Complete Java Developer Course. Learn Step by Step

In this demo project we will put in to practice the concepts we learnt about it in part 1 and part 2 of the Java tutorials. We will declare and initialize a whole bunch of different types of variable and then we will see the different ways we can use operators on them and the effect it has.

  • Learning java by building Android games

    Learning Java by Building Android Games

    Want to learn Java for Android? Even if you are completely new to either Java, Android, or game programming but are aiming to publish Android games, then this book is for you. This book also acts as a refresher for those who already have experience in Java on other platforms or other object-oriented languages.
    • Setup your own Android game programming environment using Android Studio
    • Control logic, branch your code, and add real decision-making depth to your games
    • Design and use 2d sprite animations, smooth pixel graphics, sound FX, simple collision detection and artificial intelligence (AI)
    • Build around a dozen sample test apps and 4 complete working games!
    Amazon USA
    Amazon UK
    Amazon CA
    Our Store (US only)
    small_book

    Android Game Programming by Example

    Learn to build exciting Android game projects. Build a simple flappy-bird like game to a multi-environment, tough, retro platformer then an OpenGL ES 2 Asteroids clone, running at hundreds of frames per second .
    • Animate your characters with sprite sheets, add multiple scrolling parallax backgrounds, and implement genuinely tough, playable levels in your games
    • Every single line of code is printed in the book! No need to refer to the code files while trying to follow along. All the code files are also supplied separately so you can refer to them in their completed form and copy/paste them into your project if you like.
    • Implement a multitude of other game features such as pickups, firing weapons, HUD’s, generating and playing sound FX, scenery, level transition, high scores, and more
    Amazon USA
    Amazon UK
    Amazon CA
    Our Store (US Only)

About this project

Skill level 1
Time to complete 30 minutes

New concepts

  • Outputting with Log to test and debug games

 

As we are working within the Android environment we will be working with the code that is required by all Android apps and games. We will not explain each and every part of this environment; instead, we will slowly introduce it over the course of the projects. By the end of your first real, playable game you will be very comfortable with the Android system.

This means I will ask you to take a few concepts on faith and accept that the exact under-the-hood goings on of a few of the lines of code we will write will all become clear in later tutorials or projects. So let’s get started.

Create a new Android project and enter GameVariables in the Application Name field and enter VariablesActivity in the Activity Name field. When Android Studio has finished generating the project read on.

Your screen should look something like this.

here_is_VariablesActivity.java

We need to edit the file which will contain all our Java code. So near the top of the window as indicated in the previous diagram click the VariablesActivity.java tab. You will now be faced with what looks like a rather daunting wall of code.

The good news is we don’t need hardly any of it, so go ahead and delete it all except the line of code at the very top that begins like this.

package...

Now what we will do is put in the code which we need to work within. If you read or implemented the previous 3 projects you might remember that all Android games and regular apps as well run in an Activity. An Activity is some code that will be executed when the player taps on the icon representing our game on their device. So we need to put this code in and then do all of our coding within it. Don’t bother typing it, just copy and paste this below the one remaining line of code in your  VariablesActivity.java file that starts package.... It is important that you don’t delete the line that starts with package….

If you lose track of where we are within the code then you can find the complete code listing for this project at the end of this page.
import android.app.Activity;
import android.os.Bundle;

public class VariablesActivity extends Activity {

    // This is the entry point to our game
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Our Java code will start here

        // !!Our code must end here - for now.
    }
}

The full explanation for this code is unimportant right now and exactly what it does will become clearer over later projects and tutorials but a cursory explanation will be useful- so here it is.

The first two lines we copy & pasted that begin with the import keyword, make available some code that was written by the Android development team. More specifically the code that will allow us to wrap up our own Java and make a game.

The next line that starts  public class VariablesActivity... is declaring the name of the class which will encompass our entire game. Classes as a topic are deep but do not  have to be complicated. If you can accept that our game must be wrapped up in this way then read on. If it kind of makes your head itch then sneak ahead to tutorial number 7 : Understanding OOP for coding games in Java, but be sure to come back here again afterward.

The next line of code is where the Android system does its magic and makes life easy for us.

 super.onCreate(savedInstanceState); 

This one line of code sets up our entire game ready for us to do what we want to do. We don’t need to know how it does it although we will learn more about it in later tutorials. Now, at last, we can play with what we learned about variables. Add the code below in between the two comments (repeated below for context).


// Our Java code will start here

// Let's declare and initialise a whole bunch of variables in one step
int playerScore = 0;
String playerName = "Alan Turing";
float valuePi = 3.141f;
boolean isAlive = true;

// Our next block of code will go here

// !!Our code must end here - for now.

The previous block of code simply declares a bunch of variables and initializes them in one step just as we saw in the Game variables tutorial.

Now we will print out these values. We can use some code already written for us to print out values to the Android console. Here we use the d method contained in the Log class. We then simply add a message and a variable into this method. When you read Organizing our game code with methods then methods will become clearer and when you read Understanding OOP for coding games in Java then classes will become clearer.

For now, let’s just go ahead and use this code to explore our own a little further. Enter the code after the last block of code but before the final comment.

// Our next block of code will go here
Log.d("playerScore is", "" + playerScore);

The first thing you might notice is that the Log keyword is underlined and in a red font. This indicates an error. We have this error because we need to add another line of code to import the Log class just like we imported those two other classes. No typing is required here; simply click Log to place the cursor on it and then press the Alt|Enter keyboard combination and a new line of code is added for you after the previous two import... lines of code.

This slightly strange looking line of code simply prints a message as we will see in a minute. The first pair of quotation marks contains the message "playerScore is ". The next is were we put our variable to work. The empty quotation marks are required even though they cause no output. The + playerScore simply causes the value of playerScore to be output.

Let’s add a load more of these Log.d statements to examine our other variables. Immediately below the previous Log.d... line add these.

Log.d("playerName is", "" + playerName);
Log.d("valuePi is", "" + valuePi);
Log.d("isAlive is", "" + isAlive);

Now, before we run the code let’s use some operators on our variables to sample what we learned about in the tutorial Changing the value of game variables. Add the following lines of code which change our variables using various operators and then print them out so we can see if all is as expected. Add this code immediately after the previous block.


playerScore ++;
// Just incremented player score by 1

playerName = playerName + " was quite good with numbers.";
// Yep we can add strings as well
// It is called concatenation

valuePi = valuePi + 10;
// valuePi is now 13.141.

valuePi = valuePi + playerScore;
// Now valuePi is now 13.141 + 1

isAlive = false;
// Uhh, now I'm dead

Log.d("playerScore is", "" + playerScore);
Log.d("playerName is", "" + playerName);
Log.d("valuePi is", "" + valuePi);
Log.d("isAlive is", "" + isAlive);

Now finally, attach an Android device and deploy/run the game. Note that although the output to the actual device is the same static display as our blank game project, it is the  output in the Logcat window on the  Android tab  that we are interested in. This window, pictured below should appear automatically. You will probably need to click on the image below to expand it in order to read the highlighted output.

variables_logcat_output

In the Logcat window, we can see that our variables hold the values we initialized them to and that the operators had the expected effect. We will use this technique of outputting to the Android Logcat console to help us debug our game projects.

Here is the entire code laid out with all the indentation. Note that the package... line at the top might be different to your code depending on how you built your project. It is important that this line of code remains the same way that Android Studio created it for you.

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class VariablesActivity extends Activity {

    // This is the entry point to our game
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Our Java code will start here

        // Let's declare and initialise a whole bunch of variables in one step
        int playerScore = 0;
        String playerName = "Alan Turing";
        float valuePi = 3.141f;
        boolean isAlive = true;

        // Our next block of code will go here
        Log.d("playerScore is", "" + playerScore);
        Log.d("playerName is", "" + playerName);
        Log.d("valuePi is", "" + valuePi);
        Log.d("isAlive is", "" + isAlive);

        playerScore ++;
        // Just incremented player score by 1

        playerName = playerName + " was quite good with numbers.";
        // Yep we can add strings as well
        // It is called concatenation

        valuePi = valuePi + 10;
        // valuePi is now 13.141

        valuePi = valuePi + playerScore;
        // Now valuePi is now 13.141 + 1

        isAlive = false;
        // Uhh, now I'm dead

        Log.d("playerScore is", "" + playerScore);
        Log.d("playerName is", "" + playerName);
        Log.d("valuePi is", "" + valuePi);
        Log.d("isAlive is", "" + isAlive);

        // !!Our code must end here - for now
    }
}

The logical next step would be to read the tutorial about checking for conditions in our game.

Please visit the Android category of our game coding bookstore for beginners