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

2015/4/3

Need help urgently! Stuck in infinite loop

randombruh randombruh

2015/4/3

#
Hey guys I need help asap please. So in greenFoot I use the myClara scenario its for uni. And I'm stuck on this, the goal is to move across a trail of leafs, removing the leafs as you move. Once you get off track or off the leafs you must get back on track I made a function to do this, but my problem is Clara keeps moving after she has collected all the leafs. I'm really stressed, I have spent over 8 hours in one day over this and I can't figure it out. Here is my code and a picture of what it needs to look like when its finished. Also keep in mind there are 3 other words which look similar and the code must work for those worlds also, I just need to make her stop after collecting all the leafs. This is the photo of how it starts, and how it should result: http://tinypic.com/view.php?pic=2v2jjbn&s=8#.VR4_0fmUc1J This is my code: public void run() { // TODO: Write your code below // TODO: Write your code below while(onLeaf()) { removeLeaf(); move(); while(!onLeaf()) { getBackOnTrack(); } } } public void getBackOnTrack() { turnLeft(); turnLeft(); move(); turnLeft(); move(); } }
Super_Hippo Super_Hippo

2015/4/3

#
I would probably do something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
public void act()
{
    Actor leaf = getOneObjectAtOffset(0,0,Leaf.class); //find leaf on current cell
    if (leaf != null) //if leaf is found
    {
        getWorld().removeObject(leaf); //remove leaf
        //find leaf at adjacent cell and move there:
        if (getOneObjectAtOffset(1,0,Leaf.class) != null) setLocation(getX()+1, getY());
        else if (getOneObjectAtOffset(-1,0,Leaf.class) != null) setLocation(getX()-1, getY());
        else if (getOneObjectAtOffset(0,1,Leaf.class) != null) setLocation(getX(), getY()+1);
        else if (getOneObjectAtOffset(0,-1,Leaf.class) != null) setLocation(getX(), getY()-1);
    }
}
danpost danpost

2015/4/3

#
If this is in greenfoot -- and you are calling the 'run' method from the 'act' method' -- then, all you need to do is change th first 'while' to 'if' and the second 'while' to 'else if'. The 'act' method for any active object is called repeatedly while the scenario is running (active objects being the currently set world object and any actor objects within that world). The repeated execution of the act method is what provides the 'looping' effect that you are trying to get by using the 'while' statements. In other words, instead of coding the total behavior for the lifetime of the object, you should code it for what it should do at any instance of its existence.
randombruh randombruh

2015/4/4

#
Thanks for help guys I figured it out, but thanks :)
You need to login to post a reply.