Kilobolt
  • Home
  • Tutorials
    • Game Development Tutorial >
      • Unit 1: Beginning Java >
        • Before you begin...
        • Day 1: Setting Up
        • Day 2: Java Basics
        • Day 3: More Basics
        • Day 4: Java Math
        • Day 5: More Math
        • Day 6: If... else...
        • Day 7: More Control Flow
        • Day 8: Looping
        • Day 9: More on Looping
        • Day 10: Inheritance, Interface
        • Day 11: Threads and Graphics
      • Unit 2: Creating a Game I >
        • Day 1: Foundations
        • Day 2: Basic Framework
        • Day 3: Taking User Input
        • Day 4: Enter the Robot
        • Day 5: Background and Sprites
        • Day 6: Adding Enemies
        • Day 7: Shooting Bullets
        • Day 8: Animations
        • Day 9: 2D-Arrays
        • Day 10: Painting the Tilemap
      • Unit 3: Creating a Game II >
        • Day 1: Level Creation - Part 1
        • Day 2: Level Creation - Part 2
        • Day 3: Level Creation - Part 3
        • Collision Detection Basics
        • Day 4: Collision Detection Part 1
        • Day 5: Collision Detection Part 2
        • Day 6: Collision Detection Part 3
        • Day 7: Health System & Death
        • Day 8: Basic AI & Final Touches
      • Unit 4: Android Game Development >
        • Day 1: Introduction to Android
        • Day 2: Setting up for Development
        • Day 3: Creating our First Android Application
        • Day 4: Parts of an Android Application
        • Day 5: The Android Game Framework: Part I
        • Day 6: The Android Game Framework: Part II
        • Create an Android Game From Scratch (or port your existing game)
        • Day 7: Creating an Android Game (From Start to Finish)
      • Reference Sheet
    • Zombie Bird Tutorial (Flappy Bird Remake) >
      • Unit 1: Building the Game >
        • Introduction
        • Day 1: Flappy Bird - An In-depth Analysis
        • Day 2: Setting up libGDX
        • Day 3: Understanding the libGDX Framework
        • Day 4: GameWorld and GameRenderer and the Orthographic Camera
        • Day 5: The Flight of the Dead - Adding the Bird
        • Day 6: Adding Graphics - Welcome to the Necropolis
        • Day 7: The Grass, the Bird and the Skull Pipe
        • Day 8: Collision Detection and Sound Effects
        • Day 9: Finishing Gameplay and Basic UI
        • Day 10: GameStates and High Score
        • Day 11: Supporting iOS/Android + SplashScreen, Menus and Tweening
        • Day 12: Completed UI & Source Code
    • Android Application Development Tutorial >
      • Unit 1: Writing Basic Android Apps >
        • Before you begin...
        • Day 1: Android 101
        • Day 2: Getting to Know the Android Project
        • Day 3: The Development Machine
        • Day 4: Building a Music App - Part 1: Building Blocks
        • Day 5: Building a Music App - Part 2: Intents
        • Day 6: Building a Music App - Part 3: Activity Lifecycles
  • New Forum
  • About Us
    • Contact Us
  • Our Games
    • TUMBL: FallDown
  • Facebook
  • Twitter

GAME DEVELOPMENT TUTORIAL: DAY 1-8: Looping

9/16/2012

20 Comments

 
Picture
Lesson #1-14: Introduction to Loops

In the previous lessons, we discussed conditional statements (such as the if statement) that carry out an appropriate response depending on the condition satisfied.

We will now begin covering loops, which are also often conditionally executed.

First, what is a loop? Well, as the name suggests, loops refer to code that is executed multiple times.

When is a loop useful? 
A very simple scenario: if you wanted to output a specific line of text a hundred times.
One solution to this would be to copy and paste the System.out.println(...) statement 100 times.

This is not very efficient for both the programmer and the computer. 
Instead, the proper solution would be to utilize a loop and a counter to execute one line of System.out.println(...) 100 times.

A more practical (and relevant) example is the game loop. We will have a hefty discussion about this crucial loop later, but here's a little preview of what is coming.

You will soon discover that games are very mechanical in nature. Behind the fancy graphics and beautiful sounds, there is a "heart" that causes the game to "update" its contents (move all in-game objects to the new location based on their velocity) and to render the graphics (re-draw the objects in the newly defined location). The game loop is the closest thing to this heart.

Like I said before, loops tend to be conditional. The game loop is too. 

Here's an example of a fake game loop. 
 while (playerAlive == true){

updateGame(deltaTime);
renderGame(deltaTime);

}
In this example of the while loop, if the condition playerAlive == true is satisfied, the updateGame() method and the renderGame() method will be executed.

The updateGame() method will handle things like collision or physics, while renderGame() method will display the characters and environment in the current location.

I added a deltaTime parameter to the methods, which is typically the number of nanoseconds that have passed since the previous execution of the loop. I'll explain why, although this might not have any meaning to you until you actually start game programming.

Processors, especially those found on modern mobile devices, are erratic; the speed at which the loop is executed varies. 

Why is this a problem? Let's say that updateGame() method moves a character right by 5 pixels. Now consider what would happen if updateGame() was not run at equal intervals. If the game slowed down and the loop took double the amount of time to execute again, the character would move at half speed. This would be disastrous for even a simple game like Temple Run. 

So what a lot of game developers do is this. Instead of moving 5 pixels, the character would move 5 pixels MULTIPLED BY the amount of time that elapsed since the last execution of the loop (which we can define as deltaTime). This means that no matter how much the processor slows down, the character will always travel at the same speed.

Enough with the theory. Let's meet the first loop!

Lesson #1-15: The While Loop

We saw a quick example of a while loop above. Let's discuss it in a little more depth.

The while loop will continue to execute as long as the condition is satisfied. 
Take a look at this example: 
 while (earthIsSpinning){
//The compiler will read this as:
//earthIsSpinning == true

System.out.println("The earth is still spinning.")


}
If this was an actual program, it would just flood your console as fast as the computer is capable of with the sentence "The earth is still spinning." At least for the predictable future.

We rarely want programs that run forever (unless you are running the Matrix). 
So how do you end a while loop?
Simple. When the loop is executed to your satisfaction, you change the variable earthIsSpinning to false so that the condition is no longer satisfied. Then the loop will terminate.

A full class example follows: 
 public class Looping {

public static void main(String[] args) {

boolean earthIsSpinning = true;
int counter = 0;

while (earthIsSpinning) {
System.out.println("The earth is still spinning.");
System.out.println(counter);
counter++;

if (counter >= 10) {
earthIsSpinning = false;
} // ends If

} // ends While

} // ends Main

} // ends Looping Class
Most of this code is self explanatory, because it incorporates elements that we have seen before.
Let's talk about some of the things that you may have forgotten or have unanswered questions about.

Within the main class:

1. We create a boolean earthIsSpinning, and initialize the value to be true.
2. We also create a counter and set the value as 0;

A while loop that has the condition (earthIsSpinning == true) is created.
Inside it,
1. We display "The earth is still spinning."
2. We display the value of the integer counter.
3. We add 1 to counter's value.

An if statement is contained inside the while loop.
If counter is less than 10, this if statement is ignored!

With each iteration, or execution, of the while loop, the value of the counter integer, which begins at 0, increases by 1.
This means that after the 10th display, earthIsSpinning would be set equal to false, and the condition of the while loop will no longer be satisfied, meaning that it will terminate.

Why does this if statement have to be inside the while loop? Because if we put the if statement outside the while loop, it will only run once right after the first execution of the while loop, when counter is equal to 1. The if condition will not be satisfied and the statement will never be called again.

Another way you could end the loop is by calling break; whenever you need to. That way, you don't have to stop spinning the earth to stop your loop.
_____________________

Do you ever find it difficult to count? Me neither, but let's create a counting program for the heck of it.

This program will use two values: an initial value and a final value. It will then sequentially count the integers between the two values.

_____________________ 

Figure 4: Looping Class

 public class Looping {
public static void main(String[] args) {

int initialValue = 0;
int finalValue = 10;

int counter = 0;

if (initialValue < finalValue) {
System.out.println("Input accepted!");
System.out.println("Initial Value: " + initialValue);
System.out.println("Final Value: " + finalValue);
System.out.println();
System.out.println("Initiating count.");
System.out.println();

System.out.println(initialValue);
counter++;

while (initialValue < finalValue) {
initialValue++;
System.out.println(initialValue);
counter++;

}

if (initialValue == finalValue) {
System.out.println();
System.out.println("Counting complete.");
System.out.println("There are " + counter
+ " numbers (inclusive) between "
+ (initialValue - counter + 1) + " and " + finalValue
+ ".");
}

} else {
// Executed if: if (initialValue < finalValue) above is not true.

System.out.println("Final value is less than initial value!");
System.out.println("Please choose new values.");
}

}
}
The Output: 
Picture
Try to study this code and see if you can figure out what it is doing.
It looks complex, but it is very straightforward!

We will analyze this in detail tomorrow!
_____________________


If you want to thank me for the guide, you can press Thanks or donate here or download TUMBL +!
Go to Day 7: More Control Flow
Go to Day 9: More on Looping
20 Comments
L3xx
10/29/2012 03:26:23 am

Hey there, nice tut so far.

But the output in figure 4 will never contain "the earth is still spinning".
maybe the wrong picture embeded..

greetings

Reply
James C
10/29/2012 05:50:19 am

Nice catch. Will fix that. :D

Reply
richard burns
11/11/2012 03:10:44 am

The picture does not match the code output

Reece
11/16/2012 12:45:00 pm

more good stuff thank you!

Reply
kevin
1/12/2013 06:33:07 am

Your output screen capture is missing the final statement: " There are x numbers between initial value and final value."

I'm really enjoying the tutorial so far. I've gone through several and your approach is very logical and is making some of the basics very easy to understand. Others leave some very basic structural but mportant stuff out! Thanks!!

Reply
Nathan link
1/29/2013 12:56:33 am

Great tut! Just wanted to give some feedback on my changes to both of the examples in this section(looping):

In the first example, the While loop I simplified the while by using an AND condition and achieved the same result (original is // remarked out)

public class Looping {
public static void main (String[] args) {

boolean earthIsSpinning = true;
int counter = 0;

while (earthIsSpinning && counter <10){
System.out.println("The earth is still spinning.");
System.out.println(counter + 1);
counter++;

//if (counter >= 10){
//earthIsSpinning = false;
}
}
}
//}

(sorry the comment box bonks the formatting to hell)


In the second example I simply went in and made it un-inclusive and had it tally up :

class MoreLooping {
public static void main (String[] args) {

int initialValue = 1;
int finalValue = 100;

int counter = 0;

if (initialValue < finalValue) {
System.out.println("Input accepted!");
System.out.println("Initial Value: " + initialValue);
System.out.println("Final Value: " + finalValue);
System.out.println();
System.out.println("Initiating count.");
System.out.println();

System.out.println(initialValue +1);
counter++;

while (initialValue < finalValue){
initialValue++;
System.out.println(initialValue);
counter++;
}

if (initialValue == finalValue) {
System.out.println();
System.out.println("Counting complete.");
System.out.println("There are " +(counter -1) + " numbers between "
+(initialValue - counter +1) + " and " + finalValue + ".");
}

}else {
//Executed if initalValue is < finalValue is false.
System.out.println("Final value is less than initial value!");
System.out.println("Please choose a new value.");
}
}

}

Again, sorry about the formatting, dang chat box!

Thank you again, really enjoying going through this, an aside I wanted to say you game on droid market: Tumbl is *awesome* and everyone should check that out!

Reply
Joshua Ospina
3/25/2013 03:38:11 am

This is only my second day and I already created two minigames with your help. Thanks.

Reply
Raj
4/7/2013 04:37:14 am

I think the output for the looping example is wrong

Reply
Saurabh
10/6/2013 08:40:37 am

Hi,
There is a correction in your statement which says :

"Why does this if statement have to be inside the while loop? Because if we put the if statement outside the while loop, it will only run once right after the first execution of the while loop, when counter is equal to 1. The if condition will not be satisfied and the statement will never be called again."

The if statement wont be executed at all , as the while will keep running forever as it didn't find the terminating condition to be true.
Please change that sentence.

Reply
walter
5/8/2017 08:03:00 am

Exactly! Wanted to comment on this as well. Seems still not changed. There are quite some misleading statements in this otherwise well done tuts. But as this is a beginners tut this really should´nt happen or at least be corrected. Its highly confusing for a beginner to grasp the concept of loops and this sentence does more damage than good.

Reply
Ken
10/11/2013 07:38:54 am

Hey for the last code you can also put this
public class Counter
{

static int counter = 0;

public static void main(String[] args)
{
System.out.println("I can count to 20");

while(counter <=20)
{
System.out.println();
System.out.println(counter++);
}
}

}

Reply
andrei95g link
11/23/2013 05:41:23 am

i tried to add a reverse counter on the last code, but it won't show anything....here's my code:

else if (initialValue > finalValue) {
System.out.println("challenge accepted!");
System.out.println("initial value: " + initialValue);
System.out.println("final value: " + finalValue);
System.out.println();
System.out.println("initiating count...");
System.out.println();

System.out.println(initialValue);
counter++;

while (initialValue > finalValue) {
initialValue--;
System.out.println(initialValue);
counter++;

}

if (initialValue == finalValue) {
System.out.println();
System.out.println("counter complete.");
System.out.println("there are " + counter + " numbers (inclusive) between " + (initialValue - counter + 1) + " and " + finalValue + ".");
System.out.println("and you thod you can't count on me. ha ha, got it? count... on me?... ha ha ha. now you got it?");

}

yeah, i tried to make it a little funny, don't blame me for my bad humour taste :))

Reply
Andy
12/5/2013 07:11:24 am

There are a few things
- You are starting with an "else if"
- You haven't defined your variables
- Your initialValue - counter + 1 is backwards (should be initialValue + counter - 1)

See my code below:
public class HelloWorld{

public static void main (String[] args){
int initialValue = 23;
int finalValue = 10;
int counter = 0;

if (initialValue > finalValue) {
System.out.println("challenge accepted!");
System.out.println("initial value: " + initialValue);
System.out.println("final value: " + finalValue);
System.out.println();
System.out.println("initiating count...");
System.out.println();

System.out.println(initialValue);
counter++;

while (initialValue > finalValue) {
initialValue--;
System.out.println(initialValue);
counter++;
}

if (initialValue == finalValue) {
System.out.println();
System.out.println("counter complete.");
System.out.println("there are " + counter + " numbers (inclusive) between " + (initialValue + counter - 1) + " and " + finalValue + ".");
System.out.println("and you thod you can't count on me. ha ha, got it? count... on me?... ha ha ha. now you got it?");
}
}
}
}

Reply
andrei95g
12/9/2013 11:13:23 pm

well, you are right there, but i dont want to make 2 different classes, one for counting backward and one forward. the code i have written, was an "add-on" (if i can say so) to the main code, at "Figure 4: Looping Class". so it looks like my "else is" statement is not runned even if the first "if" is not runned

buggy
2/20/2014 07:29:38 am

Nice tutorial. Thanks a lot.

Reply
Steve
4/17/2014 05:50:30 am

Great tutorials so far! I just started a couple days ago and you've done a good job explaining things. I've thought about getting into designing games since I have a background in 3D animation, but the coding involved has always been a big deterrent- it requires a lot of thought and concentra...ooh look a kitty! Now it's at least somewhat bearable. Hoping to at least get the basics down so I can build on that.

Reply
Joe K.
6/19/2014 11:13:49 am

"Why does this if statement have to be inside the while loop? Because if we put the if statement outside the while loop, it will only run once right after the first execution of the while loop, when counter is equal to 1. The if condition will not be satisfied and the statement will never be called again."

I don't understand why does it run only 1 time? Can please anyone answer me

Reply
walter
5/8/2017 08:06:51 am

It´s simply not ture. This is an error and you are sane to ask this question. The if statement would in fact never be reached as the while loop would never be exited, cause "earthIsSpinning" would never get "false".

Reply
sk8freak
8/3/2014 06:55:39 pm

So I edited the second looping class a bit to ask the user to input the values manually, and also made it so if the else statement is met to where they input incorrect values; it goes back to asking the user for input. :)

//Continues demonstrating the use of while loop
//by asking the user for values to count.

import java.util.Scanner;

public class Looping2 {

static Scanner keyboard = new Scanner(System.in);

public static void main(String[] args){

userInput();

}

static void userInput(){
int initialValue;
int finalValue;

int counter = 0;


//asking user input.
System.out.print("Please enter starting value: ");
initialValue = keyboard.nextInt();

System.out.print("Please enter the ending value: ");
finalValue = keyboard.nextInt();

if (initialValue < finalValue){
System.out.println();
System.out.println("Input accepted!");
System.out.println("Initial value: " + initialValue);
System.out.println("Final value: " + finalValue);
System.out.println();
System.out.println("Initiating countdown.");
System.out.println();

System.out.println(initialValue);
counter++;

while (initialValue < finalValue){
initialValue++;
System.out.println(initialValue);
counter++;

}

if (initialValue == finalValue){
System.out.println();
System.out.println("Counting complete.");
System.out.println("There are " + counter
+ " numbers (inclusive) between "
+ (initialValue - counter + 1) +
" and " + finalValue + ".");
}
} else {

// Executed if: if (initialValue < finalValue) above is
not true.

System.out.println("Final value is less than the
initial value.");
System.out.println("Please choose new values.");
System.out.println();

//Returns asking user for input.
userInput();
}

}
}

Reply
Adriana
12/10/2016 07:54:58 am

Figure 4: Looping Class is a beautiful example. I love how it is written. It helped me understand the REAL use of if statements WITH while loops. I said to myself, "That's how logic is done".

Reply



Leave a Reply.

    Author

    James Cho is the lead developer at Kilobolt Studios. He is a college student at Duke University and loves soccer, music, and sharing knowledge. 


© 2014 Kilobolt, LLC. All rights reserved.