I have a "battle" system, the attacker has a battle strength of e.g. 100, the defender has a strength of e.g. 75.
But I'm stuck now, I can't figure out how to find the winner. I know the attacker has a 25% chance of loosing, but I can't figure the script.
Any ideas?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With