So, what do loops have to do with programming? They are a way of repeating the same part of the code more than once. We can loop over code although potentially for a different outcome each time. This can simply mean doing the same thing until the code being looped over prompts the loop to end or it could be a predetermined number of times as specified by the loop code itself. We will look at all the types of loop that Java offers us that we will use when we build our first game. There are more that we will look at in the level two tutorials.
[widgets_on_pages id=”udemy_advert_java_1″][widgets_on_pages id=”udemy_code_details”]
While loops
Loops of the while variety are simple to understand. Think back to the if statements and their conditions. We could put the same combination of operators and variables in the conditional expression of the while loop. With the while loop we also use an expression that can evaluate to true or false. Take a look at this code.
int x = 10; while(x > 0){ x--; // x decreases by one each pass through the loop }
This is what is happening. Outside of the while loop int x is declared and initialized to 10. Then the while loop begins. Its condition is x > 0. So the while loop will continue looping through the code in its body until the condition evaluates to false. So the code above will execute 10 times.
On the first pass x equals 10 then 9 then 8 and so on. But once x is equal to 0 it is of course no longer greater than 0. Then the code will break out of the while loop and continue to run after the closing curly brace.
Just like a if statement, it is possible that the while loop will not execute even once. Take a look at this.
int x = 10; while(x > 10){ // more code here. // but it will never run unless x is greater than 10 }
Moreover, there is no limit to the complexity of the expression or the amount of code that can go in the loop body.
int playerLives = 3; int alienShips = 10; while(playerLives !=0 && alienShips !=0 ){ //Entire game code here. //... //... //etc. } //continue here when either playerLives or alienShips = 0
The above while loop would continue to execute until either playerLives or alienShips was equal to zero. As soon as one of those conditions occurred the expression would evaluate to false and the program would continue to execute from the first line of code after the while loop.
It is worth noting that once the body of the loop has been entered it will always complete; even if the expression evaluates to a false part way through as it is not tested again until the code tries to start another pass. For example.
int x = 1; while(x > 0){ x--; // x is now 0 so the condition is false // But this line still runs // and this one // and me! }
The above loop body will execute once. We can also set up a while loop that will run forever; unsurprisingly called an infinite loop. Here is one.
int x = 0; while(true){ x++; // I am going to get mighty big! }
Breaking out of a loop
We might use an infinite loop like this so that we can decide when to exit the loop from within its body. We would do this by using the break keyword when we are ready to leave the loop body. Like this.
int x = 0; while(true){ x++; // I am going to get mighty big! break; // No you're not haha // Code doesn't reach here }
And you might have been able to guess that we can combine any of the decision-making tools like if, else and switch with our while loops and all the rest of the loops, we will look at in a minute. For example.
int x = 0; int tooBig = 10; while(true){ x++; //I am going to get mighty big! if(x == tooBig){ break; } // No you're not haha. //code reaches here only until x = 10 }
It would be simple to go on for many more pages demonstrating the versatility of while loops but at some point, we want to start making games. So here is one last concept concerned with loops.
Java for loops
Java for loops have a slightly more complicated syntax than while loops as they take three parts to set up. Have a look at the code first then we will break it apart.
for(int i = 0; i < 10; i ++){ // Something that needs to happen 10 times goes here }
Here is what all the parts of the condition do.
for(declaration and initialization; condition; change after each pass through loop)
To clarify further we have:
• Declaration and initialization: We create a new
int variable
i and initialize it to
.
• Condition: Just like the other loops, it refers to the condition that must be true for the loop to continue.
• Change after each pass through the loop: In the example
i++ means that 1 is added/incremented to
i on each pass.
for(int i = 10; i > 0; i--){ // countdown } // blast off x = 0
The
for loop essentially takes control of initialization, condition evaluation and the control variable on itself. We will see some neat ways we can use this in our games in a couple of tutorials time when we learn about arrays.
[widgets_on_pages id=”udemy_advert_java_3″][widgets_on_pages id=”udemy_code_details”]
It is not hard to imagine that our code can quickly grow in length and complexity, even for a simple game. So let’s look at how we can organize our game code with methods.
Sorry but in the first example while condition using && operator. It will only evaluate true if both conditions are true, which it directly will go to false from the begining, and will keep looping until both lives and ships are 0 (Which possibly will never be) wasnt it meant to use or “||” so it evaluates true and continues running the code?
That example would be a bug am i right?
Hi Lux, thanks for your comment.
The example is meant to show that the loop will keep going until either the player or the aliens have run out of lives/ships so the && condition means that as soon as either one of them is zero the loop will end.
Hi John,
Sorry, but correct me if I’m wrong but I think Lux comment that you should use the “||” operator is the right way to use in the example. If you are going for the condition of checking whether one condition would turn to false to end the loop the correct operator would be the “||”.
I also based this using the Psuedo Code style you mentioned in the previous chapters. I will quote the above comment “the loop will keep going until either the player “”OR”” the aliens have run out of lives/ships”. But again, correct me if I’m barking off the wrong tree.
Great tutorial by the way! keep it up!
Hi there, maybe I am going mad. I have looked again and I still can’t see my error. If I explain another way(how I think it is) and if you have time tell me again where my mistake is.
while(playerLives !=0 && alienShips !=0 ){
The above code says, keep looping all the time that both playerLives and alienShips are any value other than zero. Therefore if either(or perhaps even both simultaneously) playerLives or alienships becomes zero the loop will end.
I am not saying I am right I am just not able to see the error. This could be early onset Alzheimer’s, I do have memory problems already. I hope you don’t think I am being stubborn.
Thanks for taking the time.
Hey this tutorial was pretty cool but is it possible you could give me some pointers on things like what’s the best game programming languages and a little more info on the i thing because I have edited a game that was from w3schools and there’s almost nothing that was the same but I was working on it a month ago and I messed with the i thing and the player froze on the screen.
Hi Blandon,
Thanks for your message. The i is a variable. You can read about them here. I won’t be able to give you any tips on the other tutorial because I am not familiar with it, unfortunately. As to you other question, I don’t think there is any “best” language/platform/engine but there is usually one which is most appropriate for you and your situation. To try and work out what is right for you take a look at this where do I start tutorial.
is this not the same as part 3?
Part 3 is a different subject unless you have found a bad link perhaps?