Chance of winning PHP percent calculation
Extract a random number between 0...100
, or if you prefer 0...1
.
Than check if this number is lower than 75. If it is then the attacker won.
$p = rand(0,99);if ($p<75) // Attacker Won!
This has a very straitforward probabilistic interpretation. if you extract randomly a number between 0...100
you have a 75% of chance that the number will be lower than 75. Exactly what you need.
In this case you just need rand()
function. Also notice that what @Marek suggested, the winning chance for the attacker may be much lower than 75%. (read Marek answer that points to a 57% chance of winning).
The problem will arise when you need to model more complex probability density function, example:
In this case you will need a more complex model such as a gaussian mixture.
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 better random numbers.
If I were to pop this into code as a usable function:
function attack($attack, $defend){ return (mt_rand(1, $attack) > $defend);}$attack = 100;$defend = 75;var_dump(attack(100,75));
Will simply return true or false as required. Pass in whichever values that you need.