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.
[widgets_on_pages id=”udemy_advert_java_1″][widgets_on_pages id=”udemy_code_details”]
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.
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.
[widgets_on_pages id=”udemy_advert_java_3″][widgets_on_pages id=”udemy_code_details”]
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
Now we will look at looping our game code.
Well written!! It’s better then every book I have read in the past.
There is a little Mistake in your switch.
case “Go East”:”: <- there is a double ";";
Thanks Carsten, fixed it.
You make great Tutorials, I love your writing style! As a native german speaker I would be happy if you could add some more ” , ” in the text to make reading it easier.
Sorry for my english if I spelled anything wrong
Thanks very much Johannes. I admit that the writing of some of these tutorials was a bit rushed. I am spending the next 6 months on the site adding new articles and improving the old ones. This will include working on the grammar and very likely result in the addition of quite a few commas too.
Hah! Wonderful. Its already clicking together with how you have structured this. Brilliant how you move from conditions to arguments, I see a basic idea of how classes work forming already (I think).
Thanks for your comment. Keep reading. Nothing complicated to be seen here.
Thank you for taking the time to make such well written and well thought out tutorials. These are great!
Thanks Kenny.
Can you try doing lwjgl with java now?