This site requires JavaScript, please enable it in your browser!
Greenfoot back
jam0037
jam0037 wrote ...

2012/2/29

Fleeing Worms

1
2
jam0037 jam0037

2012/2/29

#
I'm new to greenfoot and I have a small dilemma. I'm having trouble trying to devise a way to get worms to move when approached by crabs. (I'm supposed to use getObjectsInRange) So far I have this:
public void act() {
          List f = getObjectsInRange(6, Crab.class);
         if (f.size() > 0) {
          move(5);
        }
    
        }
But it doesn't work
danpost danpost

2012/2/29

#
try
public void act() {
    if (getObjectsInRange(6, Crab.class).size() > 0) {
        move(5);
    }
}
jam0037 jam0037

2012/2/29

#
They won't budge. :(
danpost danpost

2012/2/29

#
Curious! How about
 if (!getObjectsInRange(6, Crab.class).isEmpty())
jam0037 jam0037

2012/2/29

#
no cigar. The worms must really just want to be eaten.
danpost danpost

2012/2/29

#
That code is in the act() method of your Worm.class. Right?
jam0037 jam0037

2012/2/29

#
Yeah. Here's all the code for my worm class. maybe something is wrong somewhere else
import greenfoot.*;
import java.util.List;

/**
 * Worm. A sand worm. Very yummy. Especially crabs really like it.
 * Author: Michael Kolling
 */
public class Worm extends Animal
{
  /**
   * modify the worm method such that the worm moves 5
   * times when it sees a crab. The implementation should be done 
   * using either "for" or "while" loop.
   */
    public void act() {  
        if (!getObjectsInRange(12, Crab.class).isEmpty()) { 
            move();  
        }  
    }  
}
  
jam0037 jam0037

2012/2/29

#
it says to use a while loop. but I don't see how to work that in so I was just going for an if statement.
danpost danpost

2012/2/29

#
change line 17 to read move(5); and see if they move then.
jam0037 jam0037

2012/2/29

#
they won't move.
danpost danpost

2012/2/29

#
OK, saw your last post about the for or while loop. Change line 17 to read
for (int i = 0; i < 5; i++) move(1);
EDITED: and they still will not move!
danpost danpost

2012/2/29

#
What does the move() method of the Animal class look like? And there may be more than one.
jam0037 jam0037

2012/2/29

#
these things are stubborn.
jam0037 jam0037

2012/2/29

#
    /**
     * Move forward in the current direction.
     */
    public void move()
    {
        double angle = Math.toRadians( getRotation() );
        int x = (int) Math.round(getX() + Math.cos(angle) * WALKING_SPEED);
        int y = (int) Math.round(getY() + Math.sin(angle) * WALKING_SPEED);
        
        setLocation(x, y);
    }
danpost danpost

2012/2/29

#
And what is WALKING_SPEED set at?
There are more replies on the next page.
1
2