in reply to Game related OO design question

Hi,

I'm not an OO expert (Toby, where are you?), but this line is the starting point for some questions:

my $monster = Enemy->new('Rat');

You instantiate an 'Enemy' object, but not every Enemy-Object will be the same because you can instatiate several 'types' of Enemy objects. But this is exactly what OO is for. When you have several 'types' (classes) of Enemy object why don't you declare them as being of that type knowing that they share a common behaviour (Enemy).

This 'Rat' isa (certain) 'Enemy' relationship is exactly what inheritance or Roles are for.

So, aks yourself the other way: When you have a variable $e and you know that this is a reference to an Enemy, would it not be better to know whether this Enemy is a Rat but can be used everywhere an Enemy is needed in terms of behaviour?

So, without knowing the details, think about having a base class Enemy and descendants which specialize the behaviour in terms of wound, attack and defense behaviour.

Another note: You can always create helper functions or class methods for simplifying or factoring out the instantiation of that objects (kind of factory classes/objects).

I'm really interested in other comments and ideas.

Regards
McA

Replies are listed 'Best First'.
Re^2: Game related OO design question
by blindluke (Hermit) on Nov 27, 2014 at 14:59 UTC

    Thank you for the reply. I'm probably going to subclass the Enemy, but only if the design shows that it's behaviour will extend upon the base class.

    Right now, all the enemies behave in exactly the same way, in fact - there is only one enemy available. And even if I add another type of monster, and want to know what monster it is, I think that it's better to extend the traits (and make the name one of them) than to introduce inheritance.

    If I find that I need to introduce a monster that does not choose it's attack at random, but follows an attack pattern like "first light, then light, then heavy" (and thus, has a choose_attack method that is different than the default), then this would be a good argument to introduce subclasses inheriting from Enemy. If not, I'll just initialize the same class, with the same behaviour, but with a different set of traits.

    Right now, I'm not concerned with this. I'm focusing on the combat flow, and on the question of introducing attack types into the Enemy object in an elegant way, with the choose_attack() method behaving in my desired way. This is my foremost concern.

    - Luke