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

2014/2/22

Making a random fruit drop from a random place when the down arrow is pressed

hdesro hdesro

2014/2/22

#
I'm working on an assignment to make a random fruit out of apples, bananas, and pears travel down the world. They need to appear at the top in random places every time the down arrow is pressed. I have no earthly idea where to even begin. Any help would be appreciated! Thanks!
jimboweb jimboweb

2014/2/23

#
You'd want a method something like this:
    public void dropFruit()
    {
        int fruitNumber = Greenfoot.getRandomNumber(3);
        int xCoord = Greenfoot.getRandomNumber(getWidth());
        switch(fruitNumber) {
            case 0: Grapes grapes = new Grapes();
            addObject(grapes, xCoord, 0);
            break;
            case 1: Apple apple = new Apple();
            addObject(apple, xCoord, 0);
            break;
            case 2: Banana banana = new Banana();
            addObject(banana, xCoord, 0);
            break;
            case 3: Cherry cherry = new Cherry();
            addObject(cherry, xCoord, 0);
            break;
        }
    }
You wouldn't want to call it every turn or you'd have a bazillion fruit. Do it every 100 turns, which you can do by having an increasing count variable and saying if(count%100==0){dropFuit()};
jimboweb jimboweb

2014/2/23

#
Whoops, sorry, that should have been Greenfoot.getRandomNumber(4) if you have four fruit.
You need to login to post a reply.