mercredi 8 mars 2017

How to make 2 random integers, between 1 and 7, without both being 5?

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: enter image description here

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?

Aucun commentaire:

Enregistrer un commentaire