问题描述:

I've got some power up in my breakout game. The current way I'm doing it is generating a random number between 1 & 100 and check that random number: E.g

if (powerUpCheck <= 5 && ball.CanCollide && !paddle.IncreaseBatWidth && !explodingBall)

{

lblPowerUp.Visible = true;

lblPowerUp.Text = "Power Ball!";

ball.CanCollide = false;

enablePowerUp = true;

}

if (powerUpCheck <= 7 && !explodingBall && !paddle.IncreaseBatWidth && ball.CanCollide)

{

lblPowerUp.Visible = true;

lblPowerUp.Text = "Exploding Ball!";

enablePowerUp = true;

explodingBall = true;

}

if (powerUpCheck <= 20 && !paddle.IncreaseBatWidth && ball.CanCollide && !explodingBall)

{

lblPowerUp.Visible = true;

lblPowerUp.Text = "Bigger Bat!";

enablePowerUp = true;

paddle.IncreaseBatWidth = true;

}

As can tell, the 20% chance one will happen only if it's between 20 and 8 and so on

I thought about doing it like this:

if(powerUpCheck >= 20 && powerUpCheck <= 20)

But I'm not sure if that is truly 20%...

网友答案:

Code as shown checks for dependent events which may be what you are looking for (get power-up for 20%, and in 25% of that get another, probably improved version).

Usually such events would be independent and you'd just want to check for new Random number to fall in particular range:

// somewhere in class
static Random powerupRandom = new Random();

var usePowerUp1 = powerupRandom.Next(100) < 5; //(0-4 out of 0-99 - 5%)
var usePowerUp2 = powerupRandom.Next(100) < 7;    
var usePowerUp3 = powerupRandom.Next(100) < 20;

Note that if you use <= than your percentage would be different: randomValue <= 5 would have 6% chance - true for 0-5 out of 0-99.

网友答案:

For percentage stuff I prefer using Random.NextDouble() which returns a value between 0 (inclusive) and 1 (exclusive) [0,1).
Its not a big change, but you can be more precise and you do not have to change the value of your random number all the time (say from 100 to 1000).

var powerUpCheck = random.NextDouble();

//5%
if (powerUpCheck < 0.05) 
{
    //Do stuff
}

//7%
if (powerUpCheck < 0.07) 
{
    //Do stuff
}

//20%
if (powerUpCheck < 0.20)
{
    //Do stuff
}

//1 3rd
if (powerUpCheck < 1.0 / 3)
{
    //Do stuff
}
相关阅读:
Top