Application Basics With Ants (Young Developer Series, Part 3)

   
Updated 2010  

Learn about Java packages, variables, and ways that objects interact with each other through methods.

In the articles Wombat Object Basics and Wombat Classes Basics, you learned about objects, classes, methods, and language syntax. Now, in Part 3 of the Young Developer series, you'll learn what is involved in writing a Java application that relies on other Java classes (or Java API), what variables are, how to use variables, and how objects interact through methods.

As in the last article, to follow along, you will need these installed on your computer:

This article is aimed at anyone interested in Java programming who is from the age of 10 to 100 and who has no programming experience. We recommend that you have read and followed the instructions in Wombat Object Basics and Wombat Classes Basics before you move on to this article.

Looking at Packages and Variables in Ants

For this tutorial, open the Ants scenario by going to the Scenario menu, and selecting Open. The scenarios folder should automatically be visible. Choose ants, and then click Open as shown in Figure 1.

Figure 1. Opening the Ants Scenario
 

A new window opens and displays the Ants scenario. If you do not see the sand-colored world on the screen, click the Compile All button at the bottom of the scenario main screen.

Click Run and watch as ants leave their anthills and search for the piles of food. As they discover food and bring it back to the anthills, they create scented paths, or rather pheromone paths, that become more and more visible as more ants find their way to the food and back to the anthill. As with the Wombat scenario, you can place more ants or anthills on the scene. When you click Run on the ants scenario, you should see something similar to Figure 2.

Figure 2. Running the Ants Scenario
 
Import Statements and Packages

Right-click the Ant object under Actor classes, and select Open Editor. Notice the first lines of code:

import greenfoot.*;  // (World, Actor, GreenfootImage, and Greenfoot)

import java.util.Random;
import java.util.List;
import java.util.Collection;
import java.util.Iterator;
 

These are called import statements. A Java application uses import statements so that it can use other ready-made classes from the Java API, as well as other developer-created classes, or classes you create.

The first statement indicates that this application is in the greenfoot package. Packages are how Java classes are organized. Many packages are available to you, such as classes that handle math problems, that organize data in objects called Collections, and that allow you to iterate, or repeat, a process. In other words, packages bundle classes by function. Fundamental classes are in the java.lang package , and classes for reading and writing (input and output) are in the java.io package , and so on. The package statements must be the first lines in the class.

The Java API library, which contains many packages for your use, is huge, and you'll want to get familiar with what classes are available. The best way to do this is to take some time to read the API documentation. For this article, look up the java.util package . In the list on the left side of that page, notice the classes Random, List, Collection, and Iterator. Click the links to these classes and read about what they do. See if you can figure out what they do in this application. Note the methods listed for each class and see if you can find those methods being used in the code for Ants Actor Classes. You can also read more about those classes in the Java Tutorials.

Variables and Fields

Next, in the Ant class is the line public class Ant extends Actor. As you know from the previous articles, this is the class declaration statement, which tells you that this class is called Ant and that it inherits from the Actor class.

Next in the class, you'll see regular sentences marked by /** and */ symbols between lines of code. The sentences marked off by /** and */ are comments that the developer has inserted to make this code easier to understand. Comments must be marked off by either /** and */ or // so that the compiler doesn't try to read those sentences as lines of Java code.

Take a look at the following chunk of code, reading the comments that explain what the code is describing:

/** Random number generator */
private static final Random randomizer = AntWorld.getRandomizer();

/** Every how many steps can we place a pheromone drop? */
private static final int MAX_PH_LEVEL = 18;

/** How long do we keep direction after finding pheromones? */
private static final int PH_TIME = 30;

/** The speed at which the ant moves -- in pixels per update */
private static final int SPEED = 3;

// Current movement
private int deltaX = 0;
private int deltaY = 0;

/** Location of home anthill */
private AntHill homeHill;

/** Indicate whether we have any food with us. */
private boolean carryingFood = false;

/** How much pheromone do we have right now? */
private int pheromoneLevel = MAX_PH_LEVEL;

/** How well do we remember the last pheromone -- larger number: more recent. */
private int foundLastPheromone = 0;
 

All these lines of code make use of variables, and these particular variables define the fields in this Ant class. Field declarations are composed of three components, in order:

  1. Zero or more modifiers, such as public or private
  2. The field's type
  3. The field's name

But before understanding a field, you need to know more about variables. So what is a variable? In programming, a variable is assigned a value, which may or may not change. These are called variables because the values they represent usually do change. In the above code, the variable SPEED is assigned a value of 3. The value that is assigned to a variable is written on the right side of the equals sign, and the variable is written on the left.

These particular variables define the state of an object. This is similar to real-world objects, where a ball may have the state of being red or perhaps the state of being 3 feet in diameter. You might assign the variable dog the state of sleeping or awake. In the case of the Ants class, each ant can move at a speed of 3 pixels in a certain direction.

Pheromones are a scent that ants use to find food and to let other ants know where they can collect the food. In this application, the Ant class defines information about pheromone levels and how the ants act when they come across them through the field variables. For instance, the MAX_PH_LEVEL field defines the maximum number of steps that the ant can take at a pheromone drop, and foundLastPheromone defines how well the ants remember the pheromones through the use of a high or low number.

The variables are often initially set to zero, or left blank, and then those definitions change as the user plays the game.

Types of Variables

You may have noticed the keywords private, static, and final in front of the variables in this class as well as others. These keywords define what type of variable is being defined. Variables without a keyword are called instance variables, which means that the value is unique to each instance of a class -- to each object, in other words. The static variable, on the other hand, means that there is only one copy of this variable in existence, regardless of how many times the class has been instantiated, or an instance created.

Local variables are those that are used only in a method or block of code, as mentioned earlier in this article.

Access modifiers declare a variable either public or private. In the Food class, all the variables are declared private, meaning that the variable is accessible only within the Food class. If the variables were declared public, then the variable would be accessible from all classes.

Ant Objects Interact With Food Objects Through Methods

Now that the variables have been declared, they can be used in methods so that this scenario does something! Scroll down in the Ant class, and look through the methods that have been defined. You'll notice that the variables set in the beginning of the class are now being used within the methods. You will also see new variables that may only be needed for a specific method. These variables are called local variables, as mentioned earlier.

The point of the ant scenario is to collect food and return it to the anthill. Note the following checkFood method in the Ant class:

public void checkFood()
    {
        Food food = (Food) getOneIntersectingObject(Food.class);
        if (food != null) {
            takeFood(food);
        }
    }
 

In this method, a variable food of type Food is being declared. It is common in Java programming to see a class name with a capital letter, and the variable assigned to it in lowercase. This method allows the ants to interact with the food as shown in Figure 3.

Figure 3. Ants and Food Piles
 

Let's take a look at the Food class. In the Ants scenario, right-click the Food class listed under Actor Classes, and select Open Editor.

The food doesn't actually do anything but sit there, so this class just defines what Food is through its variables:

    private static final int SIZE = 30;
    private static final int HALFSIZE = SIZE / 2;
    private static final Color color1 = new Color(160, 200, 60);
    private static final Color color2 = new Color(80, 100, 30);
    private static final Color color3 = new Color(10, 50, 0);

    private int crumbs = 100;
 

Notice that these fields establish the size and color of the food. Color is created through the Color class, meaning that each color is an object, and the exact color is defined by RGB color model. The size of the piles of food are created with integers ( int) that represent the number of pixels of a particular color. All the variables are private, meaning that they can be used only in this class, and they are static, so there will be only one copy in existence, no matter how many times the class is instantiated.

Scroll down in the Color class and notice the methods in this class.As ants find and take food when the scenario is run, the appearance of that food on must change. To create this interaction between the ants and the piles of food, the takeSome method defines how much food is taken, and it calls the updateImage method so that the appearance of the food piles change, and we can see the changes.

The randomCoord method randomly scatters the colored dots over the food pile image, with more of them landing close to the middle. This method generates a random position within the food pile (to place the little green dots that represent individual bits of food). It is based on a Gaussian distribution of random numbers ( nextGaussian), which produces a higher probability for numbers closer to 0 (in what's called a "normal distribution" or a "bell curve"). The result is that the bits of food are not evenly distributed over the rectangular image surface, but are more likely to be closer to the middle, thus forming more of a "pile."

Summary

In this article, you learned how packages organize classes and how to include import statement at the top of a class. You also learned about variables and their types, and how objects interact with each other through methods. Open some of the other scenarios in Greenfoot, and take a look at the class code for each scenario object. See what variables are defined, what the methods do to interact with other methods, and what else you can learn just by looking at the code. Experiment and change some of the methods to see if you can change the behavior of objects. You can also look on the Internet for more scenarios for Greenfoot, some of which are quite complex and sophisticated, and download them.

Most of all, have fun!

For More Information