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

2013/9/14

Prepare loop method

Avast Avast

2013/9/14

#
So I want a loop to prepare all the stuff I have in my world in a random place and one class with a random number of that class in the world but I can't find a loop method that may help? Have I over looked a loop?
Gevater_Tod4711 Gevater_Tod4711

2013/9/14

#
You should use a for loop. Thats the easyest way. To add a fixed number of actors to the world you can use a for loop like this one:
1
2
3
for (int i = 0; i < numberOfActors; i++) {
    addObject(new YourActor(), Greenfoot.getRandomNumber(getWidth()), Greenfoot.getRandomNumber(getHeight()));
}
This loop will add a fixed number of your actors at random places in the world. To add a random number of actors your can use it like this:
1
2
3
4
int randomNumber = Greenfoot.getRandomNumber(10);//add something between 0 and 9 actors;
for (int i = 0; i < randomNumber; i++) {
    addObject(new YourActor(), Greenfoot.getRandomNumber(getWidth()), Greenfoot.getRandomNumber(getHeight()));
}
Avast Avast

2013/9/15

#
Do I have to repeat this for each object I want to create for the fixed actors? And what is "i".
danpost danpost

2013/9/15

#
"i" is the name of an 'int' field. In this instance it is being used as the counter for the loop. The loop will start with 'int i = 0' which will be the value for the first execution of the loop. On each subsequent execution of the loop, the value is changed (in this case by 'i++') until the condition 'i < randomNumber' becomes false, at which point the loop is not executed anymore and the statement following the loop block will be executed (if any). You will only need to use a loop when a specific set of instructions are executed multiple times. So, for those objects that only one of its type are placed in the world, you do not need to use a loop.
Peach Peach

2014/5/24

#
what is the difference between i++ and i = i + 1?
danpost danpost

2014/5/24

#
Peach wrote...
what is the difference between i++ and i = i + 1?
Absolutely nothing. Same as this: i += 1.
Peach Peach

2014/5/24

#
thank you
You need to login to post a reply.