Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android game rpg inventory system

I am using an ArrayList as my "inventory". I am having trouble figuring out a way to add multiples of the same item without taking up a spot in the "inventory". For example: I add a potion to my inventory. Now I add ANOTHER potion but this time instead of adding ANOTHER potion to the inventory, it should instead show that I have: Potions x 2, while only taking up one spot in the ArrayList. I have come up with a few solutions but I feel as if they are bad practices. One solution I tried was to add an AMOUNT variable to the item itself and increment that. Help me find a much better solution?

EDIT: Ok please ignore the above. I have gotten pretty good answers for that but what surprised me was that there were almost no tutorials on role playing game inventory systems. I've done a lot of google searching and cannot find any good examples/tutorials/source code. If anyone could point me to some good examples/tutorials/source code (does not matter what language, but preferable java, or even c/c++) I would appreciate it, thanks. Oh, and any books on the subject matter.

like image 376
semajhan Avatar asked Jul 30 '11 06:07

semajhan


2 Answers

The usual way to solve this (using the standard API) is to use a Map<Item, Integer> that maps an item to the number of of such items in the inventory.

To get the "amount" for a certain item, you then just call get:

inventory.get(item)

To add something to the inventory you do

if (!inventory.containsKey(item))
    inventory.put(item, 0);

inventory.put(item, inventory.get(item) + 1);

To remove something from the inventory you could for instance do

if (!inventory.containsKey(item))
    throw new InventoryException("Can't remove something you don't have");

inventory.put(item, inventory.get(item) - 1);

if (inventory.get(item) == 0)
    inventory.remove(item);

This can get messy if you do it in many places, so I would recommend you to encapsulate these methods in an Inventory class.

Good luck!

like image 169
aioobe Avatar answered Nov 18 '22 21:11

aioobe


Similar to aioobe's solution, you can use TObjectIntHashMap.

TObjectIntHashMap<Item> bag = new TObjectIntHashMap<Item>();

// to add `toAdd`
bag.adjustOrPutValue(item, toAdd, toAdd);

// to get the count.
int count = bag.get(item);

// to remove some
int count = bag.get(item);
if (count < toRemove) throw new IllegalStateException();
bag.adjustValue(item, -toRemove);

// to removeAll
int count = bag.remove(item);

You can create a multiples class.

class MultipleOf<T> {
    int count;
    final T t;
}

List bag = new ArrayList();
bag.add(new Sword());
bag.add(new MultipleOf(5, new Potion());

Or you can use a collection which records multiples by count.

e.g. a Bag

Bag bag = new HashBag() or TreeBag();
bag.add(new Sword());
bag.add(new Potion(), 5);
int count = bag.getCount(new Potion());
like image 6
Peter Lawrey Avatar answered Nov 18 '22 22:11

Peter Lawrey