Sunday, November 4, 2012

Quick Notes About Inventory Systems

I've been working on a small RPG and I just whipped up the inventory management code. Now, this is one of those things that most gamer's take for granted but getting this right is extremely important. Every line of code that can move an item runs the risk of either duplicating or losing the item. Here are my notes.


Styles of Inventory
Style 1: (Mostly Older RPGs)
All items are in "Inventory". Equipped items are flagged as equipped but are still listed when you press 'i'.

Pros:

  • Keeps item life cycle simple. (Monster->Player->Store)
  • No chance of losing/cloning items with equip/unequip because there is no item movement.

Cons:

  • Every bit of code that touches the inventory has to be "equipped" aware. (If an equipped item is sold/destroyed but the game forgets to run the unequip function beforehand then the player could equip another item of the same kind and get bonus stats)

Style 2: (most RPGs/WoW)
Inventory is split between "in bags" "on character"

Pros:

  • Feels more natural to the player.
  • Code that operates on bags doesn't run the risk of giving bonus stats. (Unless you have Diablo 2 style Charms)

Cons:

  • Every function that moves an item runs the risk of cloning/deleting the item.
  • 2-handed items get tricky. (is there room in the bag for both the sword and the shield)

Style 3: (Diablo 2)
Split inventory, but now items have a physical size.

Pros:

  • Theoretically the most realistic.

Cons:

  • Inventory Tetris is not a fun game.
  • Every function that moves an item runs the risk of cloning/deleting the item. Even more than Style 2 because now it's harder to check if there's room in the bag when swapping out the item.

General Tips
  • Don't worry about the overall efficiency of your code. Inventory code is rarely ran (from the processors perspective). Make it clean and easy to follow.
  • Do a full stat recalculation at the end of every function that touches an item. Don't bother trying subtract the old item and add the new. It just adds complexity, and complexity leads to bugs.
  • If you're using the concept of 2-handed weapons, don't make a special 2-hand inventory space. (As in your body is an array of locations and every item goes into the spot it's flagged for.) It's a lot less work/complexity to have a special case of putting the 2-hand item in the main-hand slot then it is to put it in the 2-hand slot and optionally unequip the main and off-hand slots.
  • You only need two equipment moving operations. A swap function which swaps an item in the inventory with an item on the body (the item can be empty). And an unequip function which finds an empty space in the inventory and then calls swap on it returning a true/false if successful.