ruk·si

Game Development
Type Object

Updated at 2013-04-12 10:52

It's a good way to create type of a game object, then instantiate game objects using that.

class Breed
{
public:
    Breed(Breed* parent, int health, const char* attack)
    : health_(health),
      attack_(attack)
    {
        // Inherit non-overridden attributes.
        if (parent != NULL)
        {
            if (health == 0) health_ = parent->getHealth();
            if (attack == NULL) attack_ = parent->getAttack();
        }
    }

    int getHealth()
    {
        return health_;
    }

    const char* getAttack()
    {
        return attack_;
    }

    Monster* newMonster()
    {
        return new Monster(*this); // Constructor...
    }

private:
    Breed* parent_;
    int health_; // Starting health.
    const char* attack_;
};
class Monster
{
    friend class Breed;

public:
    int getHealth() { return breed_.getHealth(); }
    const char* getAttack() { return breed_.getAttack(); }

private:
    Monster(Breed& breed)
    : health_(breed.getHealth()),
      breed_(breed)
    {}

    int health_; // Current health.
    Breed& breed_;
};
Monster* monster = someBreed.newMonster();
{
  "Troll": {
    "health": 25,
    "attack": "The troll hits you!"
  },
  "Troll Archer": {
    "parent": "Troll",
    "health": 0,
    "attack": "The troll archer fires an arrow!"
  },
  "Troll Wizard": {
    "parent": "Troll",
    "health": 0,
    "attack": "The troll wizard casts a spell on you!"
  }
}