I have a little problem, I will explain everything under the code:
<?php
class Fighter {
public $name;
public $health = 100;
public $power;
public $mainhand;
public function Punch($enemy) {
$arm = rand(0, 1);
if($this->mainhand == "R") {
if($arm == 1) {
$this->power = $this->power * 2;
}
}
else if($this->mainhand == "L") {
if($arm == 0) {
$this->power = $this->power * 2;
}
}
switch($arm) {
case 0:
$arm = "left";
$this->power = rand($this->power - 2, $this->power + 2);
echo $this->name . " hits " . $enemy . " with " . $arm . " arm and deals " . $this->power . " damage";
break;
case 1:
$arm = "right";
$this->power = rand($this->power - 2, $this->power + 2);
echo $this->name . " hits " . $enemy . " with " . $arm . " arm and deals " . $this->power . " damage";
break;
}
}
}
$fighter = new Fighter();
$fighter->name = "John";
$fighter->power = 7;
$fighter->mainhand = "R";
$enemy = new Fighter();
$enemy->name = "Matt";
$enemy->power = 6;
$enemy->mainhand = "L";
$fighter->Punch($enemy->name);
echo "<br>";
$enemy->Punch($fighter->name);
echo "<br><br>";
echo $fighter->name . " - " . $fighter->health . "HP";
echo "<br>";
echo $enemy->name . " - " . $enemy->health . "HP";
?>
Let me explain this code, here I have 2 "fighters" (objects), everything works fine, except I want to make that when for example John hits Matt, Matt will lose health, I tried doing like this:
$enemy->health = $enemy->health - $this->power;
But it doesn't work, I get errors:
Notice: Trying to get property of non-object
Warning: Attempt to assign property of non-object
Do you have any ideas how to make the code work the way I want?