I have a class Monster
class Monster
{
move()
attack()
}
using inheritance we could create:
melee monster : monster
overr attack()
ranged monster : monster
ovverr attack()
flying monster : monster
overr move()
swimming monster : monster
overr move()
How to create FlyingRangeMonster and MeleeSwimmingMonster without duplicating code?
I suppose we should abandon inheritance and use composition. How to realizate it in this case ?
Thank you!
You should create some methods to evaluate move or attack. If you need new monster class with the same move ability, you just override move or attack to those methods.
So for every type of monster you have one class and overridden methods, I don't see this as duplicated code.
What you are probably intending is inherit class from two classes, but it is not allowed in C# (I think it is possible in C++).
What I would do is create two interfaces, one for moving monsters and one for attacking monsters. You still need implement methods in you monster classes, but you can combine them as you wish. Also you can easily identify if your monster implements moving or attacking interface (or both) - if (myMonster is IMovingMonster) ....
You also can inherit from class and interface, so MeleeSwimmingMonster can by inherited from MeleeMonster and moving interface (or SwimmingMonster and attacking interface). For public class MeleeSwimmingMonster : MeleeMonster, IMovingMonster there you don't need to override attack() method, if it is same as in MeleeMonster class.
And if you want new ability (singing), you just create new singing interface and you can create new type of singing monsters. So your public class MeleeSwimmingSingingMonster : MeleeSwimmingMonster, ISingingMonster can do same moves and attacks as MeleeSwimmingMonster, but you can learn it some song!
Related
I am attempting to create a 2D game in Unity. Essentially, there are multiple types of 'agents': enemies and players. Programmatically, both classes 'enemy' and 'player' derive from the agent class. Then, there are different types of enemies (such as flying, ground enemies, etc).
My issue is that I need to call the Update function on all derivatives of an enemy. This is because there is code that needs to run for all enemies, and other code that should only run for some enemies - all enemies need to know where the player is, but only some enemies need to fly.
I read somewhere that you can use the new keyword, then call the base update function. However, with multiple levels of subclasses this seems inefficient and clunky as you have to state "new" for each new instance.
Is there any better way to call Update, Start and FixedUpdate (functions that are automatically called) than how I have implemented this below? Thanks in advance.
public abstract class Agent : MonoBehaviour
{
public void Start(){
// Run start code for all types of 'players', including AI
}
}
public class Enemy : Agent
{
public new void Start()
{
base.Start();
// Run start code specific to all enemies
}
}
public class WalkerEnemy : Enemy
{
public new void Start()
{
base.Start();
// Run start code specific to walking enemies ONLY
// Invoking Enemy.Start() will result in a call of Agent.Start() as well
}
}
Thank You for your help. Whilst I would call myself 'intermediate' in my programming skills, I doubt my object oriented knowledge is as fluent as it could be. So if there is some fundamental idea that I am missing, please let me know :)
First of all, when using inheritance structure, you usually want to avoid using the new keyword. Instead you mark the methods of the base class which you want to change for inheriting classes with the virtual keyword (or abstract if the baseclass does not contain code). That way you can re-use the code in the baseclass or even remove it all together.
An approach which may be even better in your case is to make an abstract method which you call in your baseclass start method. That way, inheriting classes MUST implement the method. This will be forced by the compiler.
Example:
public abstract class Agent : MonoBehaviour
{
private void Start(){
// Your code needed for all inheriting classes here.
// Call the abstract method which is defined on inheriting classes
OnStarting();
}
protected abstract void OnStarting();
}
public class Enemy : Agent
{
protected override OnStarting()
{
// Your enemy code here.
}
}
public class WalkerEnemy : Enemy
{
protected override OnStarting()
{
base.OnStarting(); // Call the code from the Enemy class
// Your walker enemy code here.
}
}
Also as you might see, I made your Start method private. Since Unity calls this by itself. You do not want to call this yourself from anywhere in your application. The OnStarting methods are marked as protected, because they should only exist/ be used in the scope of this inheritance tree.
I am having trouble understanding inheritance and implementing it in classes. I am trying to create a program with the Reptile class as the base.
What's the best way to do this with the following data?
There will also be a menu class using what I think should be a switch case to select the desired reptile and display the information.
Thanks in advance for any help.
Ok, so I understand that this is some kind of homework exercise, since in the real world you will not use inheritance for this at all.
using the the image you posted, let me try to explain inheritance in the simplest terms I can.
You can think of a base class for all reptiles - Let's call it Reptile.
This class contains all the different aspects shared by all reptiles - things like preferred food, feeding time, food to weight ratio etc'.
All of these aspects can be coded as properties of the Reptile class.
Please note that in the real world, the Species and ReptileType would also be properties of the Reptile class, making the use if inheritance completely redundant in this case - But then again, we are not talking about real world applications yet - so:
A Snake is a specific type of Reptile. A Lizard is another specific type of Reptile - so let's create classes for those two types.
So far, we have the Reptile, Snake and Lizard classes, where the last two inherits the first.
Moving on, a Cobra is a specific type of Snake, so is a Rattlesnake. So let's create classes for them inheriting from Snake. Much the same, a BeardedLizard is a specific type of Lizard, and so is a Chameleon - so here are another two classes to create.
So basically, I think your teacher is expecting to see the following:
class Reptile {/* implementation here */}
class Snake : Reptile {/* implementation here */}
class Cobra : Snake {/* implementation here */}
class Rattlesnake: Snake {/* implementation here */}
class Lizard: Reptile {/* implementation here */}
class BeardedLizard : Lizard {/* implementation here */}
class Chameleon : Lizard {/* implementation here */}
Now, the reason inheritance does not make sense in this situation, is that a Snake does not add any new capabilities to a Reptile, nor does a Chameleon to a Lizard. For inheritance to make sense, you will need to add new capabilities in the deriving types, that is specific to that class (and it's inheritors) and is not shared with the base class or any other inheritance chain of that class.
For instance, all snakes crawl, while all lizards walk. If you where to add a Crawl() method to the Snake class and a Walk() method to the Lizard class - Than it would make sense for a Snake and a Lizard class inheriting the Reptile class.
I'm writing a game and would like an opinion on my class hierarchy.
Currently I have an Character class, an AICharacter class and a KnightCharacter class.
Character holds things like Death() which all characters must facilitate, AICharacter overrides Death() with extra details for AI driven characters. KnightCharacter overrides Character stuff like handling of Shields(Only for Knights).
How can I elegantly allow my player to possess a KnightCharacter : Character and my AI to posses a KnightCharacter : AICharacter : Character?
I bascically want to only implement the AICharacter when its being controlled by an AI.
Thanks
One approach that gives a lot of flexibility is to break your characters and objects down into various aspects, where each aspect is its own class. Some examples of aspects that an action or RPG character might have are Health, Mana, WearsEquipment, UsesItems, MobileObject, PhysicalRigidbody, MeleeAttackPerformer, RangedAttackPerformer, MagicAttackPerformer, PlayerControlledMobile, AIControlledMobile, and even things like AudioSource, etc, etc... Each of these classes would derive from a common base, e.g. AspectMixin or something like that.
If you treat each of these classes as Mix-ins, then you gain a lot of flexibility in creating new archetypes that have the aspects that make sense for that type of actor. This will allow, for example, monsters and players to share the fact that they have health, but have different classes for controlling them (AI-controls vs player-controls). Further, the Health aspect can be added to a stationary object (e.g. a barrel), to allow it to be affected by damage.
To achieve this, your archetype objects store a list of aspects mixins for that archetype. Further, the aspects need to be able to query the main object for other aspects by type (or interface). It's a bit of work to set up, but that's the price of flexibility.
FWIW, this is the approach that the Unity Engine tries to encourage (consider they call them MonoBehavior: behavior..aspect...different words for the same concept), though many developers don't "get it" until they've made several failed prototypes in which classes quickly become monolithic.
To go back to your original question, it sort of depends on how many playable classes you have, and whether AI can control characters of the same classes. If so, it would best to abstract the Controls out of the characters, then have AIControls and PlayerControls derive from Controls, either of which is able to interface with your character class.
On the other hand if AI types can be broken into just a few various behaviors (aggressive monsters, peaceful NPCs), I would make each one an aspect.
What you're asking isn't possible with ordinary c# inheritance. Your brother can't have a different grandfather from you.
Since you seem to be looking for ideas, here's one that uses generics:
abstract class BaseController
{
virtual GameEvent ReadNextEvent();
}
class PlayerController : BaseController
{
override GameEvent ReadNextEvent
{
return userInterface.ReadNextEvent();
}
}
class NonPlayerController : BaseController
{
override GameEvent ReadNextEvent
{
artificialIntelligenceEngine.Think();
return artificialIntelligenceEngine.ReadNextEvent();
}
}
abstract class Character<T> where T : BaseController
{
protected T controller;
abstract ProcessEvents();
}
class KnightCharacter<T> : Character<T>
{
override ProcessEvents()
{
var e = controller.ReadNextEvent();
switch (e.Action)
{
1 : SwingSword(); break;
2 : LiftShield(); break;
3 : Yell("None shall pass!"); break;
}
}
}
class Program
{
void Example()
{
var playerKnight = new KnightCharacter<PlayerController>();
var aiKnight = new KnightCharacter<NonPlayerController>();
}
}
In order for a class to be attached to a GameObject it needs to inherit from MonoBehaviour. If I create a base character class that contains all the attributes shared by both NPCs and PCs, how do I create instances of that class and attach it to game objects? To give a concrete example of the problem, if the base character class has variables like health, stamina, strength etc, and I want a particular game object to have a particular set of those attributes, how do I attach that to a game object as it cannot inherit the base character class?
I suspect the mistake I'm making is to think that these instances need to even be attached to the objects that I want them to be associated with, but some clear guidance here would be most appreciated.
It seems that what you really want is a base class that also allows its children to be MonoBehaviours. You can accomplish this by making your base class an abstract MonoBehaviour and inheriting from it.
public abstract class Base : MonoBehaviour
{
protected int HP;
}
Then your children of this class will also be MonoBehaviours which you can attach to GameObjects.
public class Ninja : Base
{
void Start()
{
HP = 100;
}
}
I'm trying to learn interface and base classes on practical example.
Let's say that I want to to abstract Player entity
On Player.cs should be all common properties and methods for every sport in which player is assigned. So, there will be TeamSportPlayer, IndividualSportPlayer.
Again, FootballPlayer would derive from TeamSportPlayer, TennisPlayer would derive from IndividualSportPlayer and so on. All this players should have access to first class Player and their properties.
Hope I'm not too confusing.
Question is: Is this proper way of abstracting player representation in terms of oop?
How would you do this on this practical example?
Abstract classes are used for defining objects that you are never going to have an instance of. Interfaces on the other hand are used to define behaviour of objects, and interfaces are independent from the inheritance hierarchy.
Using your sports example:
Player.cs can be an abstract class. It has fields that every player has like name, age, address, etc. But you never have a "Player" on the sports field, you have a "Football player" or a "Basketball player". And the classes FootballPlayer.cs and BasketballPlayer.cs inherit from the abstract class Player.cs.
Interface on the other hand defines some common behaviour that the classes share. Usually its used to define how other classes can interact with them. So for instance, if you have classes called TennisPlayer.cs, BasketballPlayer.cs and FootballPlayer.cs you can have an interface called IHasJerseyNumber.cs. Basketball and football players have jersey numbers so they would inherit the IHasJerseyNumber.cs interface. Tennis players don't have a number and they wont inherit the interface. A totally seperate class like Referee.cs can implement the interface as well, providing he too has a jersey number (possible in some sports).
You can read more here:
Interfaces
Abstract classes