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

2021/3/16

For loops not working

BeeSauce BeeSauce

2021/3/16

#
I have a project in which I need to make a bomb emit smoke and then explode. In the world class, I have this:
public void act()
    {
        for (int i = 0; i < 5000; i++)
        {
            long currentTime  = System.currentTimeMillis();
            if (currentTime >= Wait + 25) //25ms = 1/4 second
            {
                Smoke smoke = new Smoke(Greenfoot.getRandomNumber(15) + 340,Greenfoot.getRandomNumber(9) + 1);
                addObject(smoke,280,170);
                Wait = currentTime;
            }
        }
        for (int i = 0; i < 10; i++)
        {
            Fire fire = new Fire(Greenfoot.getRandomNumber(360),10);
            addObject(fire,255,235);
        }
        Greenfoot.stop();
    }
The idea here is that it spawns smoke 5000 times, with a 1/4 second pause between each one, before spawning 10 fires all at once, and then stopping. However, when I run the code, it creates one smoke particle and 10 fires all at once and then instantly stops. I'm not sure what's going wrong here.
RcCookie RcCookie

2021/3/16

#
I assume "Wait" is initially 0. And 25ms is not a quarter of a second but a fourteeth. You should use 250 there. But that is not the main problem. The thing is the first for-loop can run really quickly, and only if it is very slow (taking the 25ms) it would spawn another instance. The much simpler solution here is using Greenfoot.delay(int) where the number specifies the number of time steps to delay. The lenght of one time step can be adjusted using the ui slider or using Greenfoot.setSpeed(int). Example implementaion:
// Inside of first for loop
Smoke smoke = new Smoke(Greenfoot.getRandomNumber(15) + 340, Greenfoot.getRandomNumber(9) + 1);
Greenfoot.delay(1);
getWorld().repaint(); // This is neccecary because the world normally only repaints in between act sequences
Now simply adjust the speed so that you like it. I would estimate that ~25 should give you 4 updates per second, but you can simply try that out. One important thing: spawning 5000 objects at a rate of 4/second takes 1250s=21m=1/3h. I think that's a pretty big explosion. And since the reset button from Greenfoot only resets in between the act loops you will have to wait that 21 minutes or restart Greenfoot if you start the execution.
You need to login to post a reply.