Reputation:
I have implemented a power up in my game and I want it to have an 10% chance to apply to the player when it kills a zombie. I have tried using this code every time the players bullet hits an zombie, but it doesn't really work.
double rand = Math.random() * 10 + 1;
if(rand == 1){
power.setShrink(true);
}
I know that the power-ups work because if I set it outside of the if-statement the player will get shrunk.
How would I make it so that it's an 10% chance for the effect to apply the player when a zombie get killed?
Upvotes: 1
Views: 77
Reputation: 39451
Doubles are floating point numbers. In you case, it can be any number from 1 to 11, up to around 53 binary digits of precision. So not only can it be 1, it can also be 1.01, 1.02, etc. Te odds of it being exactly 1 are therefore negligible.
You're better off with Random.nextInt
when generating random integers.
Random r = new Random(); //only do this once
if(r.nextInt(10) == 0){
power.setShrink(true);
}
Upvotes: 2
Reputation: 69339
You could use Random.nextInt(10)
in a similar piece of logic.
Your current code is failing because your double
is very rarely going to be exactly 1
.
Upvotes: 0
Reputation: 676
You can use a simple Monte-Carlo selection:
if(Math.random() > 0.9){
power.setShrink(true);
}
This gives you a random chance of the possibility 1 of 10 that it will trigger the power-up.
Upvotes: 1