In this quick mini-project we will practice how to test for conditions using Java in an Android game project. Condition testing is a basic staple of all programming including games. If you think it sounds complicated you will be pleasantly surprised.

  • The courses above are up to 95% off - by clicking on ad above.

About this project

Skill level 1
Time to complete 30 minutes

New concepts

  • Using variables in condition tests
  • Branching our code based upon the result

To get started create a new Android project and enter ConditionsAndBranching in the Aplication Name field and enter ConditionsAndBranchingActivity in the Activity Name field. When Android Studio has finished generating the project read on.

Delete the generated code in ConditionsAndBranchingActivity.java then enter the required code that we need to work within as shown below and as explained in the previous mini-project Game variables demo.

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

public class ConditionsAndBranchingActivity 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.
    }
}

Now we can get on with practicing our condition checking and branching. In between the two comments that denote where our code goes enter the following condition checks and branching. Be sure to read the comments in the code for a reminder of how each part of the code works. There is lots of code but don’t be put off it is not complicated. It just demonstrates in a number of different ways the concepts we discussed in the tutorials.
If the Log.d… code looks strange and alien to you be sure to read the previous mini-project Game variables demo first. Also remember to use the Alt|Enter keyboard combination to add the import… code for it as well.

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. The output is shown below.

  • The courses above are up to 95% off - by clicking on ad above.


conditions_and_branching_output

 

Be sure to run the program several times and play with the values of the variables where suggested. You are now ready for the tutorial Looping our game code.

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