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

2020/12/2

How do i make a random number?

I'm making a game where you have to collect coins but i need a way to make it spawn at a random location, can anyone help?
danpost danpost

2020/12/3

#
TheGenericDeveloper wrote...
How do i make a random number?
Here are three ways: (1) using the Greenfoot class method getRandomNumber; (2) using the java.lang.Math class random method; or, (3) creating and using a java.util.Random object Examples of each creating integer values, 0 <= x < 600, follows:
1
2
3
4
5
6
7
8
// (1)
int x = Greenfoot.getRandomNumber(600);
 
// (2)
int x = (int)(Math.random()*600);
 
// (3)
int x = (new java.util.Random()).nextInt(600);
In example (3), you probably will never find the Random object created in the same line as shown. You will normally see the Random object created separately and assigned to a object reference variable to be used multiple times, as below:
1
2
3
4
java.util.Random rand = new java.util.Random();
 
int x = rand.nextInt(600);
int y = rand.nextInt(600);
Gbasire Gbasire

2020/12/3

#
Not the best way, but a simple and easy way to it if you're a beginner : for example, you could do this in your World class : (if you have a 300 by 200 map) it will spawn some coins that I named "coin0", "coin1" etc in a random location between 0 and 300 on x axis, and 0 and 200 on y axis.
1
2
3
4
5
6
Coin coin0 = new Coin();
addObject(coin0, Greenfoot.getRandomNumber(300), Greenfoot.getRandomNumber(200);
Coin coin1 = new Coin();
addObject(coin1, Greenfoot.getRandomNumber(300), Greenfoot.getRandomNumber(200);
Coin coin2 = new Coin();
addObject(coin2, Greenfoot.getRandomNumber(300), Greenfoot.getRandomNumber(200);
Thanks!
You need to login to post a reply.