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

2014/7/16

Help With Spawning Actors Randomy

TimeScorpion7 TimeScorpion7

2014/7/16

#
Hello i have this code=:
        boolean death = false;
        
        Random generator = new Random();
        int x = 0;
   
        do{
        	
        	for(int i = 0; i < 10; i++){
        
        	x = generator.nextInt(1600) +1;
        	
        	addObject(new dot_red (), x, 10);
        		}
        
        }while(death = false);
I am trying to spawn an "asteroid" randomly along the x axis that will then fall to the ground. I have imported java.util.Random btw..
MusicPenguin MusicPenguin

2014/7/16

#
What isn't working?
MusicPenguin MusicPenguin

2014/7/16

#
If this is in your constructor your asteroid will never finish creating because you have an infinite loop in your do/while. The value of death never changes to true. Also the condition in 'while' should be ==
danpost danpost

2014/7/16

#
Basically, what you want is random falling rocks. You do not want to exacerbate the creation of these objects by using 'do' and 'for' -- you want to regulate it by using an 'if':
// instance fields
public static final generator = new Random();
private boolean death;
// in act method or in a method the act method calls
if (!death && generator.nextInt(100) < 5)
{
    addObject(new dot_red(), generator.nextInt(1600), 10);
}
davmac davmac

2014/7/16

#
MusicPenguin wrote...
If this is in your constructor your asteroid will never finish creating because you have an infinite loop in your do/while
Actually this is not correct. The condition in the do/while is "death = false", which actually sets death to false (and also evaluates to false). The loop will only ever execute once. What was probably intended was "death == false", which would indeed be an infinite loop.
MusicPenguin MusicPenguin

2014/7/16

#
What would be the point of a do/while loop only ever executing one time?
danpost danpost

2014/7/17

#
MusicPenguin wrote...
What would be the point of a do/while loop only ever executing one time?
Pretty much the same as the point in using the following:
for (boolean state = true; state; state = !state)
{
    // code to execute until 'state' is 'false'
}
or this:
boolean state = true;
while (state)
{
    // code to execute until 'state' is 'false'
    state = false;
}
That is to say, 'there is no point' (but, I seriously believe the code given by TimeScorpion7 was not intended to be limited to exactly one run-through every time).
MusicPenguin MusicPenguin

2014/7/17

#
Thanks for the answer :)
You need to login to post a reply.