andre_ss6
andre_ss6

Reputation: 1253

Design an inventory class

I'm rewriting the infrastructure for an app and I've come through an interesting situation.

I'm writing a class Bag: the class has a property Items which can hold a collection of Item's:

Weapon : Item
Armor : Item
Ammunition : Item
Bag : Item  (because a player may want to put a bag inside of another one)

Until here everything is fine, the problem is this...

In the front-end, while having different user controls for copies of a same Armor or Weapon is fine, that is not okay for Ammunition (like arrows) or Item (like breads).

A player can have, like, 50 arrows, and those need to be all represented as a single user control (a stack). The easy way to do that would be adding a Quantity property to the Item class and hide it from the Armor, Weapon and Bag classes, but that doesn't seem right, not only because I would have to hide it from the other derived classes, but also, in the end, any object in the world can exist in different quantities, so it doesn't seem right to make a class with a property like that.

It seems that the right way would be having a collection of Item's for those items which can be stacked up (something like a Stack(Of Item). So, in short: my Bag class must not only be able to hold a collection of items, but also a collection of collections of items.

For example, this is a screenshot of World of Warcraft:

As you can see, the backpack can hold both individual items and stacks of items.

How could I do that in a nice way?

Upvotes: 1

Views: 836

Answers (1)

Sayse
Sayse

Reputation: 43330

There are a couple solutions that I can think of

  1. Make a Quantity and a MaxQuantity - Then items that are singular have a MaxQuantity of 1
  2. Make a StackableItem class that ammo etc inherit from, you can then include a quantity into this and it would still allow you to carry multiple of the same item across different spaces if you wanted to. An example is shown in your screen shot of the red (armband?)

Upvotes: 5

Related Questions