You would normally have an abstract Actor
or Character
class, sub-class them, and then create instances of the sub-classes. For example:
<?php
abstract class Actor {}
abstract class Animal extends Actor {}
class Dinosaur extends Animal {}
Classes, as you know, can have properties. So one property could be $type
, which holds a string representation of the class. So if you had created an instance of Dinosaur
, $type
could simply be dinosaur
.
So now we have:
<?php
abstract class Animal extends Actor
{
protected $type;
}
class Dinosaur extends Animal
{
protected $type = 'dinosaur';
public function getType()
{
return $this->type;
}
}
class Cat extends Animal
{
protected $type = 'cat';
}
$crazyDinosaur = new Dinosaur();
$crazyCat = new Cat();
I think your problem is you’ve attached the attack()
method to the wrong class; I would attached it to the victim’s class. So if dinosaur is attacking cat, then I’d call the attack()
method on the cat class, and pass your dinosaur object as a parameter. That way, you know what’s attacking what by just inspecting what type of class the $attacker
is.
<?php
class Cat extends Animal
{
public function attack(Actor $attacker)
{
// code here to do things like deduct cat's health etc.
}
}
$crazyDinosaur = new Dinosaur();
$crazyCat = new Cat();
$crazyCat->attack($crazyDinosaur);
You can extend your attack
method to accept additional parameters. For example, the strength of the attack to change the amount of damage it does to the victim.
I’d also suggest looking into the Observer pattern, as that’s ideal in this case. Also, PHP isn’t an event-driven language so isn’t the best fit for a game.