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

2017/1/19

Why is this spawning before it equals the number?

t_k_990 t_k_990

2017/1/19

#
import greenfoot.*;
 
public class coal extends Actor
{
public void spawn_coal()
    {
        boolean spawned = false;
        while(!spawned) {
            int x = 5 + Greenfoot.getRandomNumber(getWidth()-10);
            int y = 5 + Greenfoot.getRandomNumber(getHeight()-10);
            coal myCoal = new coal();
            addObject(myCoal, x , y);
            spawned = true;
        }
        if(myCoal.getIntersectingObjects(tree.class) != null) {
                removeObject(myCoal);
                spawned = false;
            }
        }
    }    
Super_Hippo Super_Hippo

2017/1/19

#
Before it equals what number? This code should not even compile as it is.
danpost danpost

2017/1/19

#
More specifically, you should be getting something like 'cannot find symbol -- method addObject' and line 12 should be highlighted. After fixing that, you should get 'cannot find symbol -- variable myCoal' on line 15 and then 'cannot find symbol -- method removeObject' on line 16. The add and removing of objects are world object behaviors and 'myCoal' on line 15 is declared within the loop (line 11) -- its scope ends at line 14. The while loop will spawn a coal object every single time it is executed -- on its first iteration since 'spawned' is set to 'false' prior to the loop. So, there is not need for the loop (or the 'spawned' field) to get it to perform what is coded. Btw, there is an 'addedToWorld(World)' method you could use to accomplish what you trying to do. With it, you can relocate (instead of add and remove) until no tree intersects. No need for the 'spawned' field as well.
t_k_990 t_k_990

2017/1/19

#
Oops, that was the wrong script. I posted the right one here!
You need to login to post a reply.