Reputation: 151
I'm new to object-oriented programming, and I'm struggling to think of OOP.
What I want to do is a game of RPG.
I have the Hero class (the user) which has such properties: name, hair_style, power. and these methods: speak, attack, defend
I want to add more methods (spells) dynamically, as the hero learn more spells.
I do not know what is the best way to do this. I can think of the following:
Create a class 'spell' and each magic spell to have a class extends from it and add to Hero a property of type 'spell' (must be an array). When the hero try to use some spell would have to try the entire array to see if there is such magic (method). (Probably wrong)
How did you do that? Ty
Upvotes: 0
Views: 1392
Reputation: 254
You could create a base class called Ability and have spells and other hero skills derived from it. Then within your hero class, create a linked list of type Ability and call it "currentAbilities" or something like that.
Each time your hero learns a new ability, add it to the list. Each Ability can share common methods such as Cast(), Upgrade(), etc. Then when it comes time to list and use the available spells and attacks, simply read through the linked list and call their methods.
Upvotes: 1
Reputation: 3339
If you really wanted it to be dynamic, you can use the magic method __call()
(more info here) which will allow you to call functions that don't exist or are out of scope.
You're still going to have to define the functions somewhere though; this is only allows you to control the scope of the functions. You can't 'create' them dynamically in the strictest sense.
Upvotes: 0
Reputation: 1389
You could go ahead and put all of the spell methods in the class and then whenever one is called check to make sure they can use it. And if you use a class property array containing allowed spells you can check beforehand as well.
Upvotes: 1