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

2016/1/16

Spawn mushrooms randomly on my game

reportersnotebook reportersnotebook

2016/1/16

#
As you can see I have selected co-ordinates where the mushrooms should spawn each time I restart. How would I go about making these mushrooms change locations randomly each time I press the reset button?
public capworld()
    {    
        // Create a new world with 600x400 cells with a cell size of 1x1 pixels.
        super(800, 800, 1);
        outer_ring();
        inner_ring();
        addObject(new car(), 200,150);
        addObject(new mushroom(), 200,400);
        addObject(new mushroom(), 370,170);
        addObject(new mushroom(), 500,150);
        addObject(new mushroom(), 650,650);
        

    }
danpost danpost

2016/1/16

#
Use the Greenfoot class 'getRandomNumber' method to choose a number within a range of numbers. If the range was from 150 to 650, or 500 (650-150), then:
int x = 150+Greenfoot.getRandomNumber(500);
You could create a method specifically for that range (since both x- and y-coordinate ranges would be similar):
private int shroomCoord()
{
    return 150+Greenfoot.getRandomNumber(500);
}
Then, you can add a mushroom into the world with:
addObject(new mushroom(), shroomCoord(), shroomCoord());
reportersnotebook reportersnotebook

2016/1/17

#
Thank you so much it worked
You need to login to post a reply.