Code listings for "Let's Get Random," Java Magazine, January/February 2012

Listing 1
public void act() 
{
    move(4);

    if(Greenfoot.isKeyDown("left")) {
        turn(-3);
    }

    if(Greenfoot.isKeyDown("right")) {
        turn(3);
    }

    Actor pizza = getOneIntersectingObject(Pizza.class);
    if(pizza != null) {
        getWorld().removeObject(pizza);
    }
}


Listing 2
      /**
 * Act: move around (keyboard controlled) and eat pizza 
 * if we find any.
 */
public void act() 
{
    moveAndTurn();
    eat();
}
    
/**
 * Move forward and turn if the control keys are pressed.
 */
public void moveAndTurn()
{
    move(4);

    if(Greenfoot.isKeyDown("left")) {
        turn(-3);
    }

    if(Greenfoot.isKeyDown("right")) {
        turn(3);
    }
}
    
/**
 * Look for pizza and eat it if we see some
 */
public void eat()
{
    Actor pizza = getOneIntersectingObject(Pizza.class);
    if(pizza != null) {
        getWorld().removeObject(pizza);
    }
}


Listing 3
       Actor turtle = getOneIntersectingObject(Turtle.class);
if(turtle != null) {
    getWorld().removeObject(turtle);
}

Copyright 2012, Oracle Corporation