11. Simulations

What We Will Cover


Illuminations

Questions from last week or the Reading?

Midterm Questions?

  • Has anyone NOT completed the second midterm yet?
  • Midterm policy
  • Grade calculation spreadsheet in Blackboard
  • Tutoring resources
  • How do you make a program with problems compile?

Homework Questions?

11.1: Reviewing Ants

Learner Outcomes

At the end of the lesson the student will be able to:

  • Describe what is meant by the term "simulation"
  • Write code to use the Random class of the Java API
  • Write code to display a Gaussian distribution in two dimensions

11.1.1: About Simulations

  • This week we get to explore an exciting topic: computer simulations
  • A computer simulation is a program that imitates or models a particular system
  • Simulations are used for many things, from training aircraft pilots to scientific modeling
  • With simulations we can:
    • Better understand the system we simulate
    • Predict what will happen in the future
  • These two capabilties make simulations a very powerful tool
  • As an example, we worked with a simple physics simulation in lesson 7 (chapter 6)
  • The simulation was too simple to accurately predict planteary motion very far into the future
  • However, the simulation helped us to undersand how gravity interacts with objects in a planetary system
  • Before we continue, lets review some key concepts from the chapter

Concept Review

  • Simulation: an imitation of some real thing or process.
  • Computer simulation: a program that imitates or models a particular system.
  • Pheromone: chemical signals that trigger a social response in members of the same species.
  • Gaussian distribution: the normal distribution where values cluster around a mean value.
  • Emergent behavior: the way complex behavior arises out of many simple interactions.

Check Yourself

  1. Of the following, ________ is NOT an example of a simulation.
    1. a device that artifically re-creates aircraft flight
    2. a computer model of the solar system
    3. driving your car to school
    4. weather prediction
  2. True or false: a computer simulation is a simulation that runs on a computer.
  3. True or false: pheromones are chemicals used by some insects species to trigger behavior such as following a food trail.
  4. True or false: a Gaussian distribution is another term for normal distribution.
  5. True or false: it is possible for computer systems to have behaviors that are not directly traceable to specific objects, but rather to the interaction of objects.

11.1.2: Setting up the Formicarium

  • A formicarium is an enclosed area used for studying ant colonies
  • Some people may call this an ant f__m simulation
  • However, we cannot use the word ant and the word farm next to each other because the term is trademarked by Uncle Milton Toys, Inc.
  • Evidently, their lawyers send letters people who use the term "generically" (see here)
  • One person who was harassed by the lawyers was Scott Adams, the creator of Dilbert
  • He received threatening letters for using "the words" in a Dilbert comic strip
  • To resolve the issue, he was forced to write a clarification

Studing Ants

  • Ants are particularly good at foraging for food
  • Scientists study the behavior of ants and other insects to understand their successful strategies
  • Finding good strategies can help solve engineering problems in human societies, like:
    • Computer networks
    • Routing cell phone signals
    • Transmitting electricity efficiently
    • Traffic systems
  • Insects are somewhat machine-like and successful insect strategies can often be implemented on computers

Ants Scenario

  • The first simulation scenario we want to look at is Ants
  • Lets download and install this scenario:

    Scenario file: ants-2b.zip.

  • Save the file to a convenient location like the Desktop
  • Start Greenfoot and open the scenario (Greenfoot unzips the file for us)

Reviewing the Scenario

  • At this point in the development, the ants wander around looking for food
  • When an ant finds food, it brings the food back to its ant hill
  • The Creature class contains the methods for ant movement
  • The class contains a deltaX, deltaY pair used to calculate how far to move creatures
  • It solves many of the problems of how to move creatures:
    • randomWalk(): move in random directions and speeds
    • headTowards(actorObj): move toward another Actor object
    • walk(): change locations based on deltaX and deltaY
  • We will look at movement methods in more detail in the next section

Food Collection Efficiency

  • As we run the scenario, look at how long it takes the ants to collect all the available food
  • The search for food is completely random and the ants do not remember where they get food
  • In the future we will look at how ants improve the efficiency of the food collection

Check Yourself

  1. Two words commonly used for a formicarium are ________ ________.
  2. Studying ant behavior has applications in ________.
    1. routing computer networks
    2. transmitting electicity more efficiently
    3. improving traffic systems
    4. all of these
  3. True or false: the purpose of the Creature class is to contain common methods for creatures in the simulation.

More information

11.1.3: Moving Towards an Object

  • One problem we often run into in games and simulations is moving an actor towards another actor
  • This scenario solves the problem in several ways:
    • headTowards(target): adjust the walking direction towards a target actor
    • walkAwayFromHome(): walk away from the home ant hill
    • walkTowardsHome(): walk towards the home ant hill
  • All the methods work in a similar way
  • We will look at headTowards(target) since it is a more general method

Moving Towards Another Actor

  • To head towards another actor, we first get the (x, y) location of the target actor
  • We then get (x, y) location of the object we want to move towards and subtract the two:
    deltaX = target.getX() - getX();
    deltaY = target.getY() - getY();
    
  • This gives us the two components to calculate the direction of our movement vector

    A vector with (dx, dy)

  • We need to limit our movement to our maximum speed, for which we use if-statements like:
    if (deltaX > SPEED) {
        deltaX = SPEED;
    }
    if (deltaY > SPEED) {
        deltaY = SPEED;
    }
    
  • After limiting the speed, we set our new location
    setLocation(getX() + deltaX, getY() + deltaY);
    
  • Note that after we calculate the vector for moving towards an actor, it is easy to reverse direction and move away
  • To move away, we simply subtract deltaX and deltaY from our current location

Algorithm for Moving Towards Another Object

  1. Calculate the deltaX between this object and the target object
  2. Calculate the deltaY between this object and the target object
  3. Limit the deltaX so it does not exceed the maximum allowed speed
  4. Limit the deltaY so it does not exceed the maximum allowd speed
  5. Set the location of the object as (x + deltaX, y + deltaY)

Methods headTowards(), capSpeed() and walk() of Creature

public void headTowards(Actor target)
{
    deltaX = capSpeed(target.getX() - getX());
    deltaY = capSpeed(target.getY() - getY());
}

private int capSpeed(int speed)
{
    if (speed < -SPEED)
        return -SPEED;
    else if (speed > SPEED)
        return SPEED;
    else
        return speed;
}

public void walk()
{
    setLocation(getX() + deltaX, getY() + deltaY);
    setRotation((int) (180 * Math.atan2(deltaY, deltaX)
        / Math.PI));
}

Check Yourself

  1. True or false: deltaX and deltaY are the x- and y-components of the distance between two locations.
  2. To calculate deltaX, ________ the current location from the target location.
  3. To limit the length of a movement vector, we use an ________ statement with a test condition comparing the speed to a maximum speed.
  4. True or false: to move an actor you change its location.
  5. Enter the code to move an actor based on deltaX and deltaY.

    answer

11.1.4: Gaussian Distributions

  • One of the objects we added to the scenario in our homework was Food
  • One of the interesting problems we had to solve was making the piles of food look normal
  • To randomly distribute food dots in the image, we first calculated random x and y coordinates, like:
    x = Greenfoot.getRandomNumber(image.getWidth());
    y = Greenfoot.getRandomNumber(image.getHeight());
    
  • However, that made the piles of food look square as shown in Figure 9.3 of the textbook (see below)
  • We can improve the distribution by using a Gaussian (or normal) distribution

Distribution of Food Crumbs

Even distribution Normal distribution
Uniform distribution Gaussian distribution

Random Distributions

  • Many random number generators produce a distribution that is uniform
    • The chance of every possible number is the same
  • A Gaussian random number generator produces a normal distribution
  • An application like a dice game or card game needs a uniform distribution
  • We want every roll of a die or draw of a card to have the same chance
  • However, if we want to model dropping crumbs on the ground we need a normal distribution
  • Crumbs dropped on the ground normally center around a central point
  • Dropping crumbs follows the normal distribution's 68-95-99.7 rule where:
    • About 68% of observations fall within 1 standard deviation of the mean
    • About 95% of observations fall within 2 standard deviations of the mean
    • About 99.7% of observations fall within 3 standard deviations of the mean
  • We can see these standard deviations and percentages in the following diagram

Normal Distribution

Normal distribution

Check Yourself

  1. Another term for a Gaussian distribution is __________ distribution.
  2. When we want random numbers to simulate rolling dice, we need a(n) __________ distribution.
  3. Besides dropping crumbs on the ground, what other common phenomena follow normal distributions? Click to show answer
  4. To capture 99.7% of a normal population we need __________ standard deviations about the mean.

11.1.5: Getting a Normally Distributed Random Number

  • To get numbers from a Gaussian distribution, we use the Random class from the Java API
  • We construct an object from class Random in the usual way:
    Random randomizer = new Random();
    
  • After constructing an object, we can call any of its methods
  • However, the method we are interested in is the nextGaussian() method

    nextGaussian(): returns a normally distributed double value with mean 0.0 and standard deviation 1.0.

Getting a Normal Random Coordinate

  • The nextGaussian() method returns a number between -infinity and +infinity
  • However, 99.7% of the time the method will return a number between -3.0 and +3.0
  • We need to convert the random number into a positive integer within the size of the food image
  • A good strategy is to add a shifting value to the number returned
  • In this case, we could add the number 3 to the number returned
    3 + random.nextGaussian()
  • What range of numbers do we usually get now? Click to show answer
  • We then divide by 6 to get a number between 0 and 1
    (3 + random.nextGaussian()) / 6
  • Now we need to scale the number to the size of the image
    (3 + random.nextGaussian()) / 6 * size
    
  • The variable size is known as scaling the value
  • To finish, we need to handle the 0.3% of the numbers we get outside the image size
  • We can either limit the outliers to the image size or ignore them
  • One solution is presented in the following method
  • To call the method, we write code like:
    x = randomCoordinate(img.getWidth() - 1);
    y = randomCoordinate(img.getHeight() - 1);
    

Method randomCoordinate() of Class Food

private int randomCoordinate(int size) {
    int coord = (int) ((3 + randomizer.nextGaussian())
        / 6 * size);
    if (coord < 0)
    {
        coord = 0;
    }
    if (coord > size)
    {
        coord = size;
    }
    return coord;
}

Check Yourself

  1. The Java API class we use to get a Gaussian distribution is named ________.
  2. The nextGaussian() method returns a negative number ________ the time.
  3. For the following code, ________ percent of the numbers output fall between 0.0 and 1.0.
    (3 + randomizer.nextGaussian()) / 6
    
  4. For the above, ________ percent of numbers output will fall outside the range of 0.0 to 1.0.
  5. To scale a random number that is between 0.0 and 1.0, we ________ by the range we want.

Exercise 11.1

In this exercise, we add a cycle counter to the simulation.

Specifications

  1. Download the following file and save it in the scenario folder of Greenfoot.
  2. Scenario file: ants-2b.zip.

  3. Start Greenfoot and open the scenario.

    Greenfoot unzips the file for us.

  4. Open the AntWorld class and add an import statement for a List:
    import java.util.List;
  5. Also in the AntWorld class, add a private instance variable named ticks of type Counter.
    private Counter ticks = new Counter("Ticks:");

    We will use this counter to measure food collection efficiency.

  6. In the constructor of AntWorld, add the ticks variable to the world that you created in the previous step.

    Compile the class and verify there are no errors. You should see the counter display on the screen at this step. Resolve any errors you find, getting help from a classmate or the instructor as needed.

  7. Add the following act() method to AntWorld:

    AntWorld act method

  8. Compile and run your scenario to verify all the changes work well.

    If you have problems, ask a classmate or the instructor for help as needed.

  9. Run the scenario until all the food is gone. Write down the number of ticks counted until the food was collected.

    We will compare this measurement of food collection efficiency with other measurements.

  10. Save a copy of your scenario as we will be adding to it in the next exercise.

    Only submit the final scenario with all the lesson exercises completed, not the intermediate scenarios.

As time permits, read the following sections and be prepared to answer the Check Yourself questions in the section: 11.1.6: Review.

11.1.6: Review

Answer these questions to check your understanding. You can find more information by following the links after the question.

  1. Which of the following is NOT an example of a simulation? (11.1.1)
    1. Artificial re-creation of aircraft flight
    2. A computer model of the solar system
    3. Driving a car
    4. Weather prediction
  2. True or false: a computer simulation is a simulation that runs on a computer. (11.1.1)
  3. True or false: pheromones are chemicals used by some insects species to trigger behavior such as following a food trail. (11.1.1)
  4. True or false: a Gaussian distribution is another term for normal distribution. (11.1.1)
  5. True or false: it is possible for computer systems to have behaviors that are not directly traceable to specific objects, but rather to the interaction of objects. (11.1.1)
  6. Two words commonly used for a formicarium are ________ _______. (11.1.2)
  7. What is one good reason to study ant behavior? (11.1.2)
  8. What is the purpose of the Creature class? (11.1.2)
  9. What is the formula to calculate deltaX and deltaY? (11.1.3)
  10. How do we limit the length of a movement vector? (11.1.3)
  11. When we want random numbers to simulate rolling dice, we need a(n) ______________ distribution. (11.1.4)
  12. When we want to simulate dropping crumbs on the, we need a(n) ______________ distribution. (11.1.4)
  13. How many standard deviations about the mean do we need to capture 99.7% of a normal population? (11.1.4)
  14. What Java API class do we use to get a Gaussian distribution? (11.1.5)
  15. How often do we get a negative number from the nextGaussian() method? (11.1.5)
  16. For the following code, what percentage of the numbers output fall between 0.0 and 1.0? (11.1.5)
    (3 + randomizer.nextGaussian()) / 6
    
  17. What percentage of numbers output from the above will fall outside the range of 0.0 and 1.0? (11.1.5)
  18. What technique do we use to scale a random number that is between 0.0 and 1.0 to a different range of values? (11.1.5)

11.2: Adding Pheromones

Learner Outcomes

At the end of the lesson the student will be able to:

  • Implement pheromones in an ant colony simulation
  • Describe a use of simulations in solving real life problems
  • Discuss emergent behavior

11.2.1: Pheromones and the Search for Food

  • Our current population of ants randomly search for food
  • In nature, ants improve their food search through the use of pheromones

    Pheromone: chemical signals that trigger a social response in members of the same species.

  • In this lesson we add pheromones to our scenario to see how this affects the ants search for food
  • What we discover may give us ideas for solving other problems

Dropping Phermones

  • Each pheromone object represents a small drop of a chemical that ants leave on the ground
  • An important property of pheromones is that each drop evaporates fairly quickly and then disappears
  • Ants leave the pheremone drops when they return to the hill with a load of food
  • When other ants smell the pheromones, they follow the trail of drops to the food
  • By directing their search, food collection should be more efficient than random walking

Starting Class Pheromone

  • Pheromones start out strong and fade fairly quickly
  • We will need a variable to save the intensity of the pheromone
  • Also, we will display the pheromone in our simulation using an image
  • We will have our program draw the pheromone image as a circle
  • Once we have some idea what our class will do, we add class Pheromone to the simulation

Variables for Class Pheromone

private static final int MAX_INTENSITY = 180;
private int intensity;

Check Yourself

  1. Ants drop chemical signals known as __________ to tell other ants of a path to food
  2. True or false: pheromones evaporate and disappear over a short time.
  3. We can simulate the intensity of a pheromone using a(n) __________.

11.2.2: Drawing Pheromones

  • Our ants are going to drop pheromones while returning to their home with food
  • In our simulation, we will see the trail of pheromone drops as images
  • We need to simulate phermones fading with time
  • Our ants should find it harder to detect faded pheromone drops
  • One way is to shrink the size of the image we display for the pheromone
  • Ants are less likely to run into smaller images than larger images
  • We can control the size of our pheromone image with our intensity variable
  • The following is one way to write the updateImage() method

Method updateImage() of Class Pheromone

private void updateImage()
{
    int size = intensity / 3 + 3;
    GreenfootImage img = new GreenfootImage(size, size);
    int alpha = intensity / 3;
    img.setColor(new Color(255, 255, 255, alpha));
    img.fillOval(0, 0, size, size);
    setImage(img);
}

Transparency

  • Notice how the transparency of the image (alpha) is controlled by the intensity
    int alpha = intensity / 3;
    img.setColor(new Color(255, 255, 255, alpha));
    
  • The lower alpha values gives us another way to see the fading of the pheromone
  • Since we are working with colors we need to import the color library from the Java API:
    import java.awt.Color;
    
  • When the pheromone gets created, we need to call the updateImage() method from the constructor
  • After that we will use the act() method to control the fading effect

Constructor of Class Pheromone

public Pheromone()
{
    intensity = MAX_INTENSITY;
    updateImage();
}

Fading Over Time

  • With the image controlled by intensity, we simply change the intensity in the act() method
  • As you can see, we use the same recursive pattern we discussed in lesson 8.1.4
    1. Use an instance variable to control the intensity and give the variable a starting value
    2. Change the value of the intensity in the act() method
    3. Test if the intensity has reached its goal with an if-statement

Method act() of Class Pheromone

public void act()
{
    intensity--;
    if (intensity < 3)
    {
        getWorld().removeObject(this);
    }
    else
    {
        updateImage();
    }
}

Manual Testing

  • We can now manually test the Pheromone class with: new Pheromone()
  • As the scenario runs, the Pheromone object fades away and disappears

Check Yourself

  1. When first displayed, the size of the pheromone image is ________ pixels square.
  2. For the pheromone to disappear, the intensity must be less than ________.
  3. The alpha value of a pheromone is ________ when it disappears.
  4. What code would we add to updateImage() to show a small dot in the center of the image? Click to show answer

11.2.3: Dropping the Pheromones

  • Now that we have pheromones we need to get the ants to drop them
  • Our ants should drop a pheromone only when carrying food as they move towards home
  • Dropping a pheromone is a separate task so we should write a separate method
  • We will need to call the new method from the act() method
  • We can see the method below and we can test the scenario to see how it works

Ant Method act() Calls dropPheromone()

public void act()
{
    if (carryingFood) {
        walkTowardsHome();
        dropPheromone();
        checkHome();
    }
    else
    {
        searchForFood();
    }
}

private void dropPheromone() {
    Pheromone ph = new Pheromone();
    getWorld().addObject(ph, getX(), getY());
}

Tesing Pheromone Drops

  • When we test dropping the pheromone, we see that too much gets dropped into the world
  • Ants cannot produce so much pheromone and do not need to either
  • After placing a drop they need some time to produce more
  • Thus we want to delay the production and only produce one pheromone drop over several cycles
  • The textbook suggests 18 cycles as the correct amount
    private static final int MAX_PH_LEVEL = 18;
    
  • We use a constant to avoid magic numbers and make the number of cycles easy to adjust (see lesson 6.1.4)
  • What are the three steps to controlling timing over multiple scenario cycles? Click to show answer
  • Since we want the pheromone level to repeat, we reset the pheromone level after every drop
    pheromoneLevel = 0;

Updated Method dropPheromone()

private void dropPheromone() {
    pheromoneLevel++;
    if (pheromoneLevel >= MAX_PH_LEVEL)
    {
        Pheromone ph = new Pheromone();
        getWorld().addObject(ph, getX(), getY());
        pheromoneLevel = 0;
    }
}

Testing the Improvement

  • When we test the scenario now we see the drops are spread out
  • However, our ants do not follow the pheromone trail yet
  • We will add this capability in the next section

Check Yourself

  1. True or false: separate tasks should be written in their own method.
  2. What are the three steps to controlling timing over multiple scenario cycles? Click to show answer
  3. We set pheromoneLevel = 0 after adding a pheromone to the world to ________ the count.

11.2.4: Following the Trail

  • We need our ants to follow a pheromone trail
  • If an ant smells a pheromone, it should first go the the center of the drop
  • After reaching the center, the ant whould walk away from its home for some limited time
  • Why should the ant walk away from home? Click to show answer
  • Because of how the path was created, the ant is following the path to the source
  • If the ant does not shortly smell a new pheromone drop or find food, it should revert to random walking
  • The textbook provides the logic for following the path in the form of psuedocode
  • After working out the logic of a method in psuedocode we translate the method into program code

Psuedocode for Following a Pheromone Trail

if (we recently found a drop of pheromone)
{
    walk away from home;
}
else if (we smell pheromone now)
{
    walk toward the center of the pheromone drop;
    if (we are at the pheromone drop center)
    {
        note that we found pheromone;
    }
}
else
{
    walk randomly;
}
check for food;
  • The logic of searching for food belongs in our searchForFood() method
  • However, we may need a few other helper methods to support searching for food

Method searchForFood(): Psuedocode Implemented

private void searchForFood()
{
    if (foundLastPheromone > 0) {
        foundLastPheromone--;
        walkAwayFromHome();
    }
    else if (smellPheromone())
    {
        walkTowardsPheromone();
    }
    else
    {
        randomWalk();
    }
    checkFood();
}
  • Notice that we need to control the timing of the search over multiple cycles
  • Thus we add another instance variable to store the cycle counts
    private int foundLastPheromone = 0;
    
  • Also, we use a constant for the number of cycles our ants move away from home:
    private static final int PH_TIME = 30;
    
  • In addition, we implement the two helper methods
  • Note the use of collision detection in the helper methods

Method smellPheromone()

public boolean smellPheromone()
{
    Actor p = getOneIntersectingObject(Pheromone.class);
    return (p != null);
}

Method walkTowardsPheromone()

public void walkTowardsPheromone()
{
    Actor p = getOneIntersectingObject(Pheromone.class);
    if (p != null) {
        headTowards(p);
        walk();
        if (p.getX() == getX() && p.getY() == getY())
        {
            foundLastPheromone = PH_TIME;
        }
    }
}

Helper Methods

  • Notice that the above methods help searchForFood() perform its task
  • Separarate tasks should each have their own methods
  • Sometimes, one method needs another to perform its task more easily
  • These methods that help other methods are known as helper methods

Check Yourself

  1. After working out the logic of a method in ________ we translate the method into program code
  2. The name of the variable used to control how long an ant walks away from home is ________.
  3. Why does walking away from home help an ant find the next pheromone drop or food? (answer)
  4. The method call in the above helper methods that checks for a collision is ________.
  5. When a method helps another method it is known as a ________ method.

11.2.5: Path Forming

  • In nature, ants follow a phermone trail using their antennae to smell
  • After following a path they are able to recognize and remember visual clues
  • This makes traversing the path easier and faster than by using smell alone
  • In the simulation, ants also follow the trail using the technique:
    1. Go to the center of the phernome drop
    2. Head away from home for a short time
    3. If another pheromene or food is not found then resume random walking
  • Why does this work?
  • Ants go directly home when they have food, dropping pheronomes along the way
  • Thus, all pheromone drops are located directly between the food and home
  • Also, the simulation has no obstacles that ants must go around
  • With these simplifications, can we still learn about ants from our simulation?

Ant Colony Optimization Algorithms

  • It turns out that ant behavior was the inspiration for a set of optimization techniques in computer science
  • Ant colony optimization algorithms are a part of computer science studies known as swarm intelligence
  • Ant colony algorithms have produced an optimal solution to classic computer problems such as the Traveling Salesman Problem
  • The traveling salesman problem is about how to find the shortest distance between the cities on the route of a traveling salesman
  • Solutions to the problem has applications in business such as for delivery vehicles

Emergent Behavior

  • One interesting aspect of this simulation is that there is no code anywhere that talks about forming paths
  • The programmed behavior of the individual ants is quite simple:
    1. If you have food go home while dropping pheromones;
    2. If you smell pheromones go away from home;
    3. Otherwise walk around randomly;
  • However, together the ants display some sophisticated behavior
  • They form stable paths, refreshing the pheromones as they evaporate
  • Also, they efficiently transport food back to their ant hill
  • This is known as emergent behavior
  • The observed behavior is not programmed into an individual actor
  • Instead, the behavior arises from the interaction of many simple actors

Efficiency of Food Collection

  • With pheromones added, the efficiency of the food collection increases
  • We will explore how much the efficiency increases in the next exercise

Check Yourself

  1. What aspects of the simulation regarding pheromone use are realistic and where have we made simplifications?
  2. True or false: ant behavior was the inspiration for solutions to computer problems that save businesses money on deliveries.)
  3. When complex behavior arises out of simple interactions, this is known as ________ behavior.
  4. How much improvement in food collection times do you think that adding pheromones produces, if any?

More Information

Exercise 11.2

In this exercise, we test the impact of adding pheromones to the ants search for food.

Specifications

  1. Start Greenfoot and open the scenario from the last exercise.
  2. If you are reinstalling the exercise, then download your AntWorld.java file from Blackboard and save it in the unzipped scenario folder.

    If you did not complete the last exercise, then you should do so now.

  3. Create a new subclass of actor named Pheromone, open the editor and copy this code to the new class.

    Compile the class after copying in the code and verify there are no errors. Resolve any errors you find, getting help from a classmate or the instructor as needed.

  4. Open the Ant class and add the following constants and instance variables:
    private static final int MAX_PH_LEVEL = 18;
    private int pheromoneLevel = 0;
    
    private static final int PH_TIME = 30;
    private int foundLastPheromone = 0;
    

    Compile the class after copying in the code and verify there are no errors. Resolve any errors you find, getting help from a classmate or the instructor as needed.

  5. In the Ant class and add the following methods:
    private void dropPheromone() {
        pheromoneLevel++;
        if (pheromoneLevel >= MAX_PH_LEVEL)
        {
            Pheromone ph = new Pheromone();
            getWorld().addObject(ph, getX(), getY());
            pheromoneLevel = 0;
        }
    }
    
    public boolean smellPheromone()
    {
        Actor p = getOneIntersectingObject(Pheromone.class);
        return (p != null);
    }
    
    public void walkTowardsPheromone()
    {
        Actor p = getOneIntersectingObject(Pheromone.class);
        if (p != null) {
            headTowards(p);
            walk();
            if (p.getX() == getX() && p.getY() == getY())
            {
                foundLastPheromone = PH_TIME;
            }
        }
    }
    

    Compile the class after copying in the code and verify there are no errors. Resolve any errors you find, getting help from a classmate or the instructor as needed.

  6. In the Ant class replace the act() method with the following:
    public void act()
    {
        if (carryingFood) {
            walkTowardsHome();
            dropPheromone();
            checkHome();
        }
        else
        {
            searchForFood();
        }
    }
    

    Compile the class after copying in the code and verify there are no errors. Resolve any errors you find, getting help from a classmate or the instructor as needed.

  7. In the Ant class replace the searchForFood() method with the following:
    private void searchForFood()
    {
        if (foundLastPheromone > 0) {
            foundLastPheromone--;
            walkAwayFromHome();
        }
        else if (smellPheromone())
        {
            walkTowardsPheromone();
        }
        else
        {
            randomWalk();
        }
        checkFood();
    }
    
  8. Compile and run your scenario to verify all the changes work well.

    At this point your ants should drop phomones when they carry food and follow the pheromone trails when searching. If you have problems, ask a classmate or the instructor for help as needed.

  9. Run the scenario until all the food is gone. Write down the number of ticks counted until the food was collected.

    We will compare this measurement of food collection efficiency with other measurements.

  10. Assume that pollution has introduced a toxic substance into the ant's environment, such that the time between dropping pheromones is 4 times as long. Change the MAX_PH_LEVEL as follows and rerun the scenario until all the food is collected. Record the number of ticks counted for comparison with previous settings.
    private static final int MAX_PH_LEVEL = 18 * 4;
    
  11. Restore the MAX_PH_LEVEL setting and assume instead that another pollutant has decreased the ant's ability to remember when they smelled a pheromone. Instead of 30 steps they can only remember for 10 steps. Change the PH_TIME constant and rerun the scenario until all the food is collected. Record the number of ticks counted for comparison with previous settings.
    private static final int PH_TIME = 30 / 3;
    
  12. Save your completed scenario to upload to Blackboard as part of assignment 9.

As time permits, read the following sections and be prepared to answer the Check Yourself questions in the section: 11.2.6: Review.

11.2.6: Review

Answer these questions to check your understanding. You can find more information by following the links after the question.

  1. Ants drop chemical signals known as _____________ to tell other ants of a path to food (11.2.1)
  2. We can most easily simulate the intensity of a pheromone over time using: (11.2.1)
    1. an actor
    2. a chemical
    3. a variable
    4. a method
  3. Which of the following code statements add a small dot in the center of the GreenfootImage variable named img? (11.2.2)
    1. img.fillRect(size / 2, size / 2, 2, 2);
    2. img.drawLine(size / 2, size / 2, 2, 2);
    3. img.drawDot(size / 2, size / 2);
    4. img.setcolorAt(size / 2, size / 2);
  4. True or false: images can change size as a scenario runs. (11.2.2)
  5. To make a single object disappear from a scenario, use the following code in the class for the object:
    1. getWorld().removeObject(this);
    2. getWorld().removeLastObject();
    3. getWorld().removeObjects(getObjects(this));
    4. removeFromWorld(anObject);
  6. True or false: images can change transparency as a scenario runs. (11.2.2)
  7. Which of the following is NOT part of controlling timing of multiple scenario cycles? (11.2.3)
    1. Declare and initialize a counter instance variable.
    2. Change the value of the counter in the act() method.
    3. Use an if-statement to test if the counter has reached its goal.
    4. Call the setImage() method of the actor.
  8. Which of the following is a good reason to use a constant? (11.2.3)
    1. To document numbers
    2. To reduce code size
    3. To obfuscate numbers
    4. To use a static variable
  9. True of false: separate tasks should be written in their own method. (11.2.3)
  10. Methods that help other methods do their job are known as ___________ methods. (11.2.4)
  11. True or false: psuedocode can show us the logic of a method. (11.2.4)
  12. True or false: to follow a pheromone path an ant needs to walk away from home. (11.2.4)
  13. True or false: a simulation mimics real world behavior exactly. (11.2.5)
  14. True or false: ant behavior was the inspiration for solutions to computer problems that save businesses money on deliveries. (11.2.5)
  15. When complex behavior arises out of simple interactions, this is known as __________________ behavior. (11.2.5)

11.3: Dialogs

Learner Outcomes

At the end of the lesson the student will be able to:

  • Describe what is meant by a GUI
  • Collect user input in an input dialog box
  • Confirm information with a confirmation dialog
  • Show messages using a message dialog

11.3.1: Foxes and Rabbits

  • The textbook provides a complete simulation known as foxes and rabbits
  • The scenario attempts to predict the relationship in populations between an isolated population of foxes and rabbits
  • Lets download and install this scenario:

    Scenario file: foxes-and-rabbits.zip.

  • Save the file inside the Greenfoot scenarios folder.
  • Start Greenfoot and open the scenario (Greenfoot unzips the file for us)

Examining the Scenario

  • The scenario is interesting and we looked at it during our homework
  • However, the scenario has an extra feature not discussed in the textbook
  • An extra window pops up and displays a graph
  • The graph window is created by a Plotter object
  • The Plotter object is constructed in the Field world in the usual way
  • Looking at Plotter in more detail, we see class types like JFrame and JLabel
  • JFrame and JLabel are part of the GUI somponent library that comes with Java

Graphical User Interfaces

  • GUI is an acronym for Graphical User Interface
  • Graphical User Interface (GUI) -- pronounced "gooey"
    • Graphical: not just text or characters but includes windows, menus, buttons, etc.
    • User: person using the program via mouse, keyboard, etc.
    • Interface: interaction with the program using visual controls, widgets, etc.
  • Note that Greenfoot uses some standard GUI components -- where are they?
  • We will take a closer look at some GUI components in the following sections

Check Yourself

  1. GUI stands for G________ U________ I________.
  2. True or false: Java has a standard GUI libarary.
  3. What GUI components does Greenfoot itself use?

11.3.2: Java's GUI Libraries

  • GUIs provide a graphical way to interact with a program
  • The program presents information and users can enter information
  • Users interact with GUI components using a mouse, keyboard or other input device
  • Most modern applications use a GUI
  • Typical graphical components include:
    • Window: portion of screen providing an area for the other components
    • Button: looks like a button that can be pressed
    • Labels: Displays text or images in the window
    • Text field: place where users can type values
  • We can see the typical GUI components in the following image

Example GUI

input dialog

Java's GUI Libraries

  • GUIs are built from objects called components:
    • Also called controls or widgets
  • Java provides two sets of GUI components: AWT and Swing
  • AWT (Abstract Window Toolkit) is the older set of components:
    • Relies on the underlying visual components of the operating system
    • AWT GUIs look different on every operating system
  • Swing (like the dance) is the newer set of components:
    • Extends AWT components and adds new capabilities
    • Components draw their own visual shapes on the screen
    • GUIs look about the same on every operating system
  • The inheritance hierarchy below shows how Swing extends AWT
  • Note that Swing components all start with the letter "J"
  • As we can see, the GUI libraries are extensive with over 250 classes in Swing alone
  • We will focus on only a small part in this lesson: JDialog

Inheritance Hierarchy for GUI Components

components hierarchy

Check Yourself

  1. True or false: Java has two GUI libraries: AWT and Swing.
  2. True or false: Swing components all start with the letter "S" (for Swing).
  3. True or false: Swing components extend AWT components.

11.3.3: User Dialogs

  • Sometimes we need a user to enter information into our scenario
  • For example, we want their name to add to a high score list
  • Other times we may want to provide them with a help window
  • One easy way to solve these problems is to use dialog boxes

Making a Dialog

  • Dialogs provide a simple "popup" type of interaction with users
  • JOptionPane provides several static methods for constructing dialogs
  • Code for dialogs can be minimal
  • For instance, to collect text input from a dialog:
    String inputString = JOptionPane.showInputDialog(
        "Enter your first name:");
    
  • Produces the following input dialog:

    input dialog

  • Most dialogs are small windows with minimal options like the above

Example Dialog Scenario

  • Let's look at a simple scenario that demonstrates how to use dialogs:

    Scenario file: dialogs.zip.

  • The scenario has three simple classes:
    • DialogWorld: constructs the world and adds a Dialog object
    • Telephone: displays an image, rings and starts the dialog sequence when clicked with a mouse
    • Label: provides a simple way to display text in the scenario
  • We will use three types of dialog boxes in sequence:
    1. showInputDialog: ask for name
    2. showConfirmDialog: verify entry
    3. showMessageDialog: display results
  • These dialogs are created in the makeDialog() method of Dialog

Method makeDialog() of Class Telephone

public void makeDialog()
{
    inputStr = JOptionPane.showInputDialog(
        "Hello, who is this?");
    buttonNbr = JOptionPane.showConfirmDialog(
        null, "Are you sure?");
    String msg = "First name: " + inputStr
         + "\nButton number: " + buttonNbr
         + "\nPress OK or Enter key to exit.";
    JOptionPane.showMessageDialog(null, msg);
}

Input Dialogs

  • We use the showInputDialog() method of JOptionPane to get text input from users
  • In the above example, we created the first dialog like this:
    inputStr = JOptionPane.showInputDialog(
        "Hello, who is this?");
    
  • Notice that we created the dialog in a single statement

Confirmation Dialogs

  • We use the showConfirmDialog() method of JOptionPane to confirm information
  • The method will provide the user with three buttons: Yes, No and Cancel
  • In the above example, we created the first dialog like this:
    buttonNbr = JOptionPane.showConfirmDialog(
        null, "Are you sure?");
    
  • Again, notice that we created the dialog in a single statement

Message Dialogs

  • We use the showMessageDialog() to show the user a message
  • From the above example:
    String msg = "First name: " + inputStr
         + "\nButton number: " + buttonNbr
         + "\nPress OK or Enter key to exit.";
    JOptionPane.showMessageDialog(null, msg);
    
  • Notice the "\n" character sequences in the above code
  • These are known as newline characters and start a new line in text
  • Dialogs let us use newline characters to layout text within our message string

Commonly-Used Methods of JOptionPane

Static Method Description
showConfirmDialog Asks a confirming question, like yes/no/cancel and returns an int number corresponding to the button pressed.
showInputDialog Prompts for user text input and returns a string containing the text entered by the user.
showMessageDialog Displays a message and waits until the user presses a button in confirmation.

Check Yourself

  1. True or false: dialog boxes can be constructed using class JOptionPane.
  2. True or false: dialogs can be created with a single statement.
  3. The type of data returned by the showInputDialog() method is ________.
  4. The type of data returned by the showConfirmDialog() method is ________.

11.3.4: Dialog Arguments

  • Most methods of JOptionPane that create dialogs are overloaded to provide display options
  • These options control dialog placement, messages and icons displayed, and title-bar wording
  • Both showInputDialog() and showMessageDialog() accept the arguments listed in the table below
  • For example, one method of showInputDialog() can accept four arguments:
    JOptionPane.showInputDialog(parentComponent, messageString,
        titleString, messageTypeInt);
    
  • To display a different dialog without an input field:
    JOptionPane.showMessageDialog(parent, message);
    
  • If the parent component is unknown, we use null for that argument
    JOptionPane.showMessageDialog(null, "Hello, world!");
    
  • Note that we cannot use our main Greenfoot window as a parent compoent
  • Thus, we normally use null as the parent argument
  • We can look up the exact usage for the various methods in the JOptionPane API documentation

Commonly-Used Arguments in JOptionPane Methods

Argument Description
parentComponent An object representing the frame of the dialog box and controls its placement on the screen. If null is used, the dialog is centered on the screen.
messageString A descriptive message displayed in the dialog box.
titleString A title typically placed in the title bar above the dialog box.
messageTypeInt Indicates the type of icon to display in the dialog box. Choosing one of the message types shown below will display the corresponding icon.
icon Used if you want to display your own icon image rather than a built-in icon.

Icons provided by JOptionPane

Metal Windows Message Type Description
metal error windows error ERROR_MESSAGE Displays an error icon.
metal info windows info INFORMATION_MESSAGE Displays an information icon.
metal warning windows warning WARNING_MESSAGE Displays an warning icon.
metal question windows question QUESTION_MESSAGE Displays an question icon.
    PLAIN_MESSAGE Does not display an icon.

Check Yourself

  1. True or false: we can adjust the look of dialogs by changing arguments to the creation methods.
  2. True or false: we can set text in the title bar of a dialog.
  3. Enter a statement that creates an input dialog with the following options:
    1. A message that says, "Enter your name:".
    2. A title that says, "Winner".
    3. An icon that displays a question mark.

    answer

More Information

11.3.5: Adding Dialogs to a Greenfoot Scenario

  • Let us look at how we can add dialogs to our scenario

Step-by-Step Procedure for Adding Dialogs

  1. The first step is to decide which class will conduct the dialog
    • In our example, the class is named Telephone
  2. The next step is to import JOptionPane:
    import javax.swing.JOptionPane;
  3. Set up a condition, usually in our act() method, that starts the dialog

    In our example, we used a mouse click:

    if (Greenfoot.mousePressed(this)) {
        // ...
        makeDialog();
        // ...
    }
    
  4. Next, construct the sequence of dialog statements and save the user input we need
    public void makeDialog()
    {
        inputStr = JOptionPane.showInputDialog(
            "Hello, who is this?");
        buttonNbr = JOptionPane.showConfirmDialog(
            null, "Are you sure?");
        String msg = "First name: " + inputStr
             + "\nButton number: " + buttonNbr
             + "\nPress OK or Enter key to exit.";
        JOptionPane.showMessageDialog(null, msg);
    }
    

Dialog Modality

  • Note that dialogs are modal: they stop the scenario from running until the user finishes her input
  • This is usually the behavior you want
  • Why keep running a game while the user is looking at the instructions dialog?
  • If we do not want modal behavior we will need a different approach
  • We will look at more user input options later in the course

Check Yourself

  1. Import the ________ API library when using dialogs.
  2. True or false: a scenario stops running while a dialog is displayed and resumes when the dialog is closed.
  3. The reason to use an if-statement in the act() method when creating a dialog is that the dialog ________ the scenario.

11.3.6: Project Dialog

  • Over the next few weeks we will work on the final course project
  • You have wide freedom in defining your project, though there are requirements to meet
  • A project is a powerful way to develop a deeper understanding of programming
  • You will work with many of the Java and Greenfoot features to develop your project
  • At the end you will have created a program you can be proud of
  • You will develop your project over four phases as shown below
  • You will have about one week to complete each phase

Project Phases

  1. Project proposal: define what your project is about
  2. Initial prototype: find out if your core concepts work
  3. User-testable prototype: get suggestions from other students
  4. Final project: the final version (at least for this course)

Exercise 11.3

In this exercise, we explore the use of dialogs in Greenfoot.

Specifications

  1. Download the following file and save it in the scenario folder of Greenfoot.
  2. Scenario file: dialogs.zip.

  3. Start Greenfoot and open the scenario.

    Greenfoot unzips the file for us.

  4. Open the Telephone class and locate the makeDialog() method.

    We will use this method to create our dialogs.

  5. Change the first dialog to ask the user to enter a name.

    Save the answer in the variable inputStr.

  6. Add another instance variable to the Telephone class, like:
    private String codeStr;
  7. Add a second input dialog statement asking the user to enter a code and save the answer in the above variable.

    For more information on input dialogs see section: 11.3.3: User Dialogs.

  8. Construct a message like the following:

    String msg = "Your name is " + inputStr + " and the code is " + codeStr + ". \nIs this correct?";

  9. Show a dialog with the above message, and save the answer the user enters in the variable buttonNbr.

    For more information on confirmation dialogs see section: 11.3.3: User Dialogs.

  10. If the user pressed the No or Cancel button, then return from the method immediately.

    Hint: buttons are numbered from left to right with the first button on the left being number 0.

  11. If the user entered the code "42" (without the quotation marks), then show a message dialog saying, "The meaning of life." Otherwise, show a message dialog saying, "Wrong code. Try entering the number 42."

    For more information on message dialogs see section: 11.3.3: User Dialogs.

  12. Compile and run your scenario to verify all the changes work well.

    If you have problems, ask a classmate or the instructor for help as needed.

  13. Save your Telephone.java file to submit to Blackboard as part of assignment 9.

As time permits, read the following sections and be prepared to answer the Check Yourself questions in the section: 11.3.7: Review.

11.3.7: Review

Answer these questions to check your understanding. You can find more information by following the links after the question.

  1. GUI stands for G___________ U_________ I___________. (11.3.1)
  2. True or false: Java has a standard GUI libarary. (11.3.1)
  3. What are three components typically used in GUIs? (11.3.2)
  4. True or false: Java has two GUI libraries: AWT and Swing. (11.3.2)
  5. True or false: Swing components all start with the letter "S" (for Swing). (11.3.2)
  6. True or false: Swing components extend AWT components. (11.3.2)
  7. True or false: dialog boxes can be constructed using class JOptionPane. (11.3.3)
  8. What is the name of the method to create input dialogs? (11.3.3)
  9. What is the name of the method to create confirmation dialogs? (11.3.3)
  10. What is the name of the method to create message dialogs? (11.3.3)
  11. True or false: dialogs can be created with a single statement. (11.3.3)
  12. What type of data does the showInputDialog() method return? (11.3.3)
  13. What type of data does the showConfirmDialog() method return? (11.3.3)
  14. True or false: we can set text in the title bar of a dialog. (11.3.4)
  15. Write a statement that creates an input dialog with the following options: (11.3.4)
    1. A message that says, "Enter your name".
    2. A title that says, "Winner's name".
    3. An icon that displays a question mark.
  16. Which API library do you import when using dialogs? (11.3.5)
  17. True or false: a scenario stops running while a dialog is displayed and resumes when the dialog is closed. (11.3.5)

Wrap Up

Due Next:
A8: Image Manipulation (4/25/12)
A9: Project Proposal (5/2/12)
  • When class is over, please shut down your computer
  • You may complete unfinished lesson exercises at any time before the due date.
Home | Blackboard | Schedule | Syllabus | Room Policies
Help | FAQ's | HowTo's | Links
Last Updated: April 29 2012 @00:45:34