Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chance of winning PHP percent calculation

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?

like image 490
Sims Avatar asked Jan 07 '15 15:01

Sims


3 Answers

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.

like image 167
Rob W Avatar answered Nov 18 '22 17:11

Rob W


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:

enter image description here

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

like image 23
dynamic Avatar answered Nov 18 '22 16:11

dynamic


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.

like image 3
John Reid Avatar answered Nov 18 '22 17:11

John Reid