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

The Complete Java Developer Course. Learn Step by Step

The Complete Android & Java Developer Course – Build 21 Apps

Master Android N App Development With Java

We have seen in the last tutorial how we can detect certain conditions in our code. For example when the player loses a life, destroys an alien or gets a new fastest time. We have also seen the Java if keyword that allows us to execute a certain block of code when a certain condition or conditions are met. It is this concept of branching our code based on certain conditions that we need to explore a little further.

About this tutorial

Skill level 1
Time to read: 10 minutes

New Concepts:

  1. Branching in Java
  2. Else
  3. Switch

We will explore two key ideas conditional branching which is really just a closer look at if and some more related keywords and conditional looping which allows us to repeat some code if certain conditions are met.

Conditional branching

As with many topics in Java, you could write a whole book on structuring code. What we will do is cover just enough so we can start to make games. Here are the vital ways we can conditionally branch our code. Let’s have some fun with branching.

If they come over the bridge shoot them

The captain is dying and, knowing that his remaining subordinates are not very experienced, he decides to write a Java program to convey his last orders after he has died. The troops must hold one side of a bridge while awaiting reinforcements. The first command the captain wants to make sure his troops understand is this:

If they come over the bridge, shoot them.

So how do we simulate this situation in Java? We need a boolean variable isComingOverBridge. The next bit of code assumes that the isComingOverBridge variable has been previously declared and initialized. We can then use if like this.

if(isComingOverBridge){

	// Shoot them

}

If the boolean isComingOverBridge is true the code inside the opening and closing curly braces will run. If not the program continues after the if block and without running it.

  • 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)

Else do this instead

The captain also wants to tell his troops what to do (stay put) if the enemy is not coming over the bridge. Now we introduce another Java keyword  else. When we want to explicitly do something when the if does not evaluate to true, we can use else. We can then use it like this to tell the troops to stay put if the enemy is not coming over the bridge:

if(isComingOverBridge){

	//Shoot them

}else{

	//Hold position

}

The captain then realized that the problem wasn’t as simple as he first thought. What if the enemy comes come over the bridge, but has more troops? His squad would be overrun. So, he came up with this code (we’ll show some variables as well this time.):

boolean isComingOverTheBridge;
int enemyTroops;
int friendlyTroops;
// Code that initializes the above variables one way or another

//Now the if
if(isComingOverTheBridge && friendlyTroops > enemyTroops){

	//shoot them

}else if(isComingOverTheBridge && friendlyTroops < enemyTroops) {

	//blow the bridge

}else{

	//Hold position

}

And finally, the captain’s last concern was that if the enemy came over the bridge waving the white flag of surrender and were promptly slaughtered, then his men would end up as war criminals. The Java code needed being obvious. Using the wavingWhiteFlag boolean variable he wrote this test:

if (wavingWhiteFlag){

	//Take prisoners

}

But where to put this code was less clear. In the end, the captain opted for the following nested solution and changing the test for wavingWhiteFlag to logical NOT, like this:

if (!wavingWhiteFlag){ // not surrendering so check everything else

	if(isComingOverTheBridge && friendlyTroops > enemyTroops){

		// shoot them

	}else if(isComingOverTheBridge && friendlyTroops < enemyTroops) {

		// blow the bridge

	}

}else{ // this is the else for our first if

	// Take prisoners

{

// Holding position

This demonstrates that we can nest if and else statements inside of one another to create even deeper decisions. We could go on making more and more complicated decisions but what we have seen is more than sufficient to make some fairly complex games.

Switching to make decisions

Sometimes a decision in Java can be better made in other ways. When we have to make a decision based on a clear list of possibilities that doesn’t involve complex combinations wide ranges of values, then switch is usually the way to go. We start a switch decision like this.

switch(argument){

}

In the previous example, argument could be an expression or a variable. Then within the curly braces, we can make decisions based on the argument with case and break elements.

case x:
	//code to for x
	break;

case y:
	//code for y
	break;

You can see in the previous example each case states a possible result and each break denotes the end of that case and the point that execution leaves the switch statement. We can also use default without a value to run some code in case none of the case statements evaluate to true. Like this:

default: // Look no value
	// Do something here if no other case statements are true
	break;

Supposing we are writing an old-fashioned text adventure game, the kind of game where the player types command like “Go East”, “Go West”, “Take Sword” etc. In this case, switch could handle that situation like this example code and we could use default to handle the player typing a command which is not specifically handled.

// get input from user in a String variable called command
switch(command){

	case "Go East":
		// code to go east
		break;

	case "Go West":
		// code to go west
		break;

	case "Take sword":
		// code to take the sword
		break;

	//more possible cases

	default:
		// Sorry I don't understand your command
		break;

}
If you would like to practice what you have learnt in this and the previous tutorial about checking for conditions try the mini-project Checking for conditions and branching demo.

Now we will look at looping our game code.