I want to make an inventory/equipment system to interface with my item system. My item system is an inherited class system based around shared properties.
I store types in enums and give the items an enum value.
My inheritance structure:
Item {
Equippable {
Armor {Chest, Head}
Weapon {Melee, Ranged}
}
}
I have each subType define an enum variable in its parent class, so Chest would define the armorTypes enum in an explicit base constructor call with the type.
e.g.
public enum armorTypes {Chest, Helmet}
public class Armor : Equippable
{
armorTypes armorType;
public Armor(armorTypes at) : base(equippableTypes.Armor)
{
armorType = at;
}
}
public class Chest : Armor
{
int defense = 10;
public Chest() : base(armorTypes.Chest) {}
}
public class Helmet : Armor
{
int defense = 5;
public Helmet() : base(armorTypes.Helmet) {}
}
In my Inventory class I have blank versions of these items.
Inventory{
public Chest chestSlot;
public Helmet helmetSlot;
public Melee meleeSlot;
public Ranged rangedSlot;
}
I want to compare the objects in the two slots based on their properties.
void Compare(Item item)
{
switch((item as Armor).armorType)
{
case armorTypes.Chest :
Console.WriteLine((item as Chest).defense + " or " + chestSlot.defense);
break;
case armorTypes.Helmet :
Console.WriteLine((item as Helmet).defense + " or " + helmetSlot.defense);
break;
}
}
However, when I cast it using the as keyword, somehow I lose my instance?
Also, as I need to access item.armorType I cannot encapsulate Armor, can I?
This is how I'd implement this. First of all, let the base class define basic comparison methods:
Next, we must define some default equipment. Armor:
Weapon:
Note, that there's no any enums here. This is because the type itself (e.g.,
Chest
,Helmet
, etc.) defines, where concrete item belongs to. Enum is just superfluous here.Here's the inventory:
Note, that internally inventory uses a collection to store its items. This allow to perform batch operations with items (like comparison, implemented in
Compare
method).Now, let's define some new types of items and test our inventory:
The test: