Chance to get a percentage of PHP

I have a “battle” system, the attacker has the power of battle, for example. 100, the defender has a strength of, for example, 75.

But I'm stuck now, I can’t figure out how to find a winner. I know that an attacker has a 25% chance of losing, but I can’t determine the script.

Any ideas?

+7
php random probability
source share
4 answers

Extract a random number between 0...100 or if you prefer 0...1 .
Then check to see if this number is greater than 75. If this happens, the attacker will win.

 $p = rand(0,99); if ($p<75) // Attacker Won! 

This has a very simple probabilistic interpretation. if you randomly extract a number between 0...100 , you have a 75% chance that the number will be below 75. Exactly what you need.

In this case, you only need the rand() function. Also note that, as @Marek suggested, a winning chance for an attacker could be well below 75%. (read Marek’s answer, which indicates a 57% chance of winning).

The problem arises when you need to model a more complex probability density function, for example:

enter image description here

In this case, you will need a more complex model, such as a Gaussian mixture .

+15
source share

The probability of winning a player A against B is A / (A + B), this is for any number and any scale. Then use a dynamic response to calculate the actual result.

In your example:

 $c = (75/(100+75)); // 0.42857142857142857143 $Awon = mt_rand(0, 9999) < ($c * 10000); 
+3
source share

If I used this code as a useful function:

 function attack($attack, $defend) { return (mt_rand(1, $attack) > $defend); } $attack = 100; $defend = 75; var_dump(attack(100,75)); 

Will just return true or false as needed. Go depending on what you need.

+3
source share

Using a random number generator, you can create a function such as:

 function chance($percent) { return mt_rand(0, 99) < $percent; } 

Then you can use the function anywhere. Note: mt_rand supposedly generates the best random numbers.

+1
source share

All Articles