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

2017/4/15

Adding actor at random method problem

vermox vermox

2017/4/15

#
I am using a couple of methods that I think danpost suggested for adding actors (in this case bombs) to random empty spaces in my world. The code is:
public MyWorld(){
     super(600, 600, 1); 
     Bomb bomb1 = new Bomb();
     Bomb bomb2 = new Bomb();
     addToRandomEmptyCell(bomb1);
     addToRandomEmptyCell(bomb2);
}


public int getRandomNumber(int start,int end)
    {
        int normal = Greenfoot.getRandomNumber(end-start+1);
        return normal+start;
    }

    private void addToRandomEmptyCell(Actor actor)
    {
        int x = 0, y = 0;
        while (!getObjectsAt(x, y, null).isEmpty())
        {
            x = getRandomNumber(50, 550);
            y = getRandomNumber(50, 550);
        }      
        addObject(actor, x, y);
    }
The problem is that the first bomb is always at 0,0. If I change the initial x, y values the first bomb is always at that location. The second bomb is always random though. What is this happening and what could I do to fix it?
danpost danpost

2017/4/15

#
Change line 19 to this:
while (x == 0 || !getObjectsAt(x, y, null).isEmpty())
Where you got this code, I believe there was always an actor alreay located at (0, 0). Because you do not have one at that location, you need the extra check in the loop.
vermox vermox

2017/4/15

#
Thanks very much! Works perfectly now.
You need to login to post a reply.