Android game rpg inventory system

前端 未结 5 880
不知归路
不知归路 2021-01-12 04:37

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 exam

5条回答
  •  孤街浪徒
    2021-01-12 05:11

    The usual way to solve this (using the standard API) is to use a Map 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!

提交回复
热议问题