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

2017/10/23

Using loops to add objects in my prepare methd.

Faheem Faheem

2017/10/23

#
Hey guys I want to add 10 ducks and 10crocodiles at random locations in my world so when I click run or reset it should change. At the moment I have just copied and pasted it 10 times in my prepare method but it looks very crowded and I'm not so familiar with loops. Any help plz I would aprreciate it.
danpost danpost

2017/10/23

#
A simple loop looks like this:
int loopLimit = 10;
int count;
for (count = 0; count < loopLimit; count++)
{
    // code to repeat
}
The 'count = 0' part is the initial value. The 'count < loopLimit' part is the condition to execute the block of 'code to repeat'. The 'count++' part is executed immediately after the block is actually executed and before the condition is checked to see if it should be executed again. If the value of 'count' is not needed outside the loop and the loop limit is always the same, it can be written as follows:
for (int count = 0; count < 10; count++)
{
    // code to repeat
}
In your case, you have two things you want to do ten times, which is adding a duck and a crocodile at random locations. Best would be to add a method that adds an Actor object at a random location in your world:
private void addActorAtRandomLocation(Actor actor)
[
    int x = Greenfoot.getRandomNumber(getWidth());
    int y = Greenfoot.getRandomNumber(getHeight());
    addObject(actor, x, y);
}
Now, you can simply use the following loop:
for (int i=0; i<10; i++)
{
    addActorAtRandomLocation(new Duck());
    addActorAtRandomLocation(new Crocodile());
}
You need to login to post a reply.