EDIT: This is a different question to How do I generate random integers within a specific range in Java? because I requested the solution uses the methods
public int getRandomNumber(int start,int end)
{
int normal = Greenfoot.getRandomNumber(end-start+1);
return normal+start;
}
and
getRandomNumber(int, int)
Good afternoon. I've been working on a project in Greenfoot, with Java, where the main character is on a 7x7 screen with 3 coins. I have written this code:
public class FirstLevel extends World
{
public int getRandomNumber(int start,int end)
{
int normal = Greenfoot.getRandomNumber(end-start+1);
return normal+start;
}
/**
* Constructor for objects of class FirstLevel.
*
*/
public FirstLevel()
{
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(9, 9, 60);
MainCharacter theDuckDude = new MainCharacter ();
addObject(theDuckDude, 4, 4);
coin coin1 = new coin();
coin coin2 = new coin();
coin coin3 = new coin();
addObject(coin1, getRandomNumber(1, 7), getRandomNumber(1, 7));
addObject(coin2, getRandomNumber(1, 7), getRandomNumber(1, 7));
addObject(coin3, getRandomNumber(1, 7), getRandomNumber(1, 7));
}
}
So, as you can see, the three coins and duck character will appear on the screen in random locations. Here is a snippet of the code from my theDuckDude character:
Actor actor = getOneIntersectingObject(coin.class);
getWorld().removeObject(actor);
Obviously, this code shows that when my theDuckDude character touches the coin actor, the coin is removed. As you have probably seen, this poses quite a problem: if theDuckDude and a coin actor are generated on the same square, the game won't work properly:
So, is there a way I can generate these random ints, using the
public int getRandomNumber(int start,int end)
{
int normal = Greenfoot.getRandomNumber(end-start+1);
return normal+start;
}
and
getRandomNumber(1, 7)
methods, how can I make it generate a random location that excludes 5 and 5 together?