I'm beggining in OOP with PHP, and i want to make 2 opponent fight, with the function fight. I want to have a $degat variable which is a result of a radom number between 1 to strength of attacker - (minus) dexterity of defender. So the result must be of minimum 0.
I have this code and when I var_dump it I still have negative value. I can't see what i'm doing wrong.
public function fight(Fighter $target)
{
// $degat = (rand(1, $this->strength) - $target->dexterity) >= 0 ? (rand(1, $this->strength) - $target->dexterity) : 0;
if ((rand(1, $this->strength) - $target->dexterity) > 0) {
$degat = (rand(1, $this->strength) - $target->dexterity);
} else {
$degat = 0;
};
var_dump($degat);
$target->life -= $degat;
}
thanks !
CodePudding user response:
Well, the problem here is the fact that each time you call rand, the result is different. So, you should save the expression with rand and then reuse it.
Also, the whole thing could be done slightly shorter with the use of ternary operator.
$expr = (rand(1, $this->strength) - $target->dexterity);
$degat = $expr > 0 ? $expr : 0
Some notes:
rand
does not generate cryptographically secure values and could also depend on the staring seed, you could also consider usingrandom_int
, I think it helps randomizing your game, for sureread more about ternary operator here: https://www.php.net/manual/en/language.operators.comparison.php
CodePudding user response:
Instead of storing the result of rand(1, $this->strength) - $target->dexterity)
in a variable, you could also omit the if-statement completely and reduce your method to:
public function fight(Fighter $target)
{
// max(a,b) returns the higher number from a and b
$target->life -= max(0, rand(1, $this->strength) - $target->dexterity);
}