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

2014/7/3

Random Number Generator

CaptainMorgan CaptainMorgan

2014/7/3

#
How can I make a random number generator when I press a key i.e. space. I need it so it doesn't show a series of numbers in a certain sequence and so that a number doesn't get selected twice. Also I need it so a counter will appear over the selected number, basically it's a game of bingo. My code so far (unworking) for the random generator:
1
2
3
4
5
Used_1=1;
                if (Greenfoot.isKeyDown("space")) { 
                    setImage (new GreenfootImage("27 - 26 ?", 46, Color.BLACK,Color.WHITE));     
                    Greenfoot.delay (120);     
                    getWorld().addObject(new Counter(), 28, 28);
Zamoht Zamoht

2014/7/3

#
You should look at the Greenfoot method getRandomNumber(int limit). You use it like this: Greenfoot.getRandomNumber(someNumber); From the API: "Return a random number between 0 (inclusive) and limit (exclusive)." To make sure that the same number is not selected twice you should generate the number inside a loop. Then you can just keep generating a new number until the number matches criteria you set up inside the loop.
NikZ NikZ

2014/7/3

#
Zamoht wrote...
You should look at the Greenfoot method getRandomNumber(int limit). You use it like this: Greenfoot.getRandomNumber(someNumber); From the API: "Return a random number between 0 (inclusive) and limit (exclusive)."
If you don't want 0 and you want, for example, 2 to 14 (inclusive), you can simply add 2 to getRandomNumber(13)
danpost danpost

2014/7/3

#
How are you displaying the numbers? are they Actors or are you drawing them onto the background of the world? If they are Actors, you can give them an instance int field to hold the number they display. Then, if you remove the actor when its number is chosen (and replace it with a counter -- as if covering the number), then you would only need to randomly choose one of the number displaying actor from those that are still in the world, Because you are removing chosen ones, one cannot be picked more than once. Because you are choosing the number displaying actor itself, you can place the counter at its location before removing the number actor. If needed you can add a 'get' method to return the number the actor displays -- in case you need to show which number was chosen elsewhere.
You need to login to post a reply.