Skip to content
Advertisement

I want the minimum to be 0 but the substraction is still negative

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 !

Advertisement

Answer

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);
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement