Choosing a random object

I’ve made a Pong game and I’ve just added power ups.

The game contains a class named PowerUps and a few specific power up classes which all extends PowerUps.
I would like to make a method that randomly picks one of all the power ups I’ve made. How would I make this and where should I place it?

Supposed the powerups are singletons, just place them in an array and pick a random Object (Math.random) otherwise you could create a factory class for each power up and place them in such an array. Then you would pick a random factory and it would create a powerup for you.

-ClaasJG

You could just give every power up its own propability for example powerup1 has a chance of 0.01 and a probability that no powerups drop.
After that you could just use Math.random method and get a value that you use to determine what powerup drops.

So Every powerup that extends PowerUps class should have probability value (from 0 to 1). Then you use Math.random and
check if it matches with any probabilites that your powerups have.

Rough example in code:

if(Math.random() == powerup.getProbability()){
	//Create powerup
}else if(Math.random() == powerup2.getProbability){
	//Create powerup2
}

This method might not be the best, but it works. As for the placement I can’t help.

[quote][…]Math.random() == powerup.getProbability()[…]
[/quote]
That will ‘never’ be true. Supposed you want probabilitys you could sum up all probabilitys and then generate a random number equals to the sum. Now you could simply iterate over all options, summing up the probabilitys for each returning the option the moment the sum is bigger than the number.

[url=http://pastebin.java-gaming.org/3a97d9d60201e]Example[/url] [i](In ProbChoser  you have to remove the 'IllegalArgumentException' in line 33.)[/i]

-ClaasJG

If you want to randomly choose 1 from a list of power-ups, you can do the following:


// Assume your power ups share a common base class and are all in a list
public List<PowerUp> powerUps;

// Chose a random element from the list
Random rand = new Random();
PowerUp randomPowerUp = powerUps.get(rand.nextInt(powerUps.size()));