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

2013/11/13

Call Pause() or Wait() within a Loop to visualize steps?

GreenJ GreenJ

2013/11/13

#
The concept of the Run button invoking an infinite loop of act( ) calls is quite straight forward. Even without the knowledge of loops, beginners can write programs, just by conditional moves within the act method. On the other hand, some methods (Clean Code!) just include loops, or at least a finite amount of move( ) commands -- e.g. goAroundTree( ). Such pieces of code will be displayed as a single jump. Trying wait or pause methods didn't lead to the expected result, i.e. refreshing the world within a method call or loop. Is there a chance to solve this? Or is merely the act method capable of refreshing the world? Cheers GreenJay
danpost danpost

2013/11/13

#
The Greenfoot class 'delay' method will lead to the expected result by itself. However, it has the drawback of stopping everything within the scenario for the allotted time. Better would be to add an instance int field to be used as a timer, incrementing it each act cycle. When it reaches a specified limit, reset it to zero and perform the action needed. For example, in a world class
// with instance fields
Turtle turtle = new Turtle();
int timer;
// in the world constructor
addObject(turtle, 100, 100);
// sample act method
public void act()
{
    timer = (timer+1)%50; // increments and resets to zero when needed
    if (timer == 0) turtle.move(5);
}
The turtle will move a distance of 5 pixels once every second (approximately).
danpost danpost

2013/11/14

#
Of course, this can be done in the Turtle class itself; and be made to do specific things at specific times. Like in the following:
// instance field
int timer;
// sample act method
public void act()
{
    timer++;
    if (timer == 30) move(5); // move
    if (timer == 60 && size > 2) // multiply
    {
        for (int i=0; i<2; i++)
        {
            Turtle turtle = new Turtle();
            turtle.setSize(size/2);
            turtle.setRotation(getRotation()-60+120*i);
            getWorld().addObject(turtle, getX(), getY());
        }
    }
    if (timer == 90) getWorld().removeObject(this); // die
}
You need to login to post a reply.