Android游戏RPG库存系统

sem*_*han 8 java android arraylist

我使用ArrayList作为我的"库存".我无法找到一种方法来添加同一项目的多个而不占用"库存"中的一个点.例如:我在我的库存中添加药水.现在我添加另一种药水,但这次不是在库存中添加另一种药水,而是应该显示我有:药水x 2,而只占用ArrayList中的一个点.我想出了一些解决方案,但我觉得它们好像是不好的做法.我尝试过的一个解决方案是将一个AMOUNT变量添加到项目本身并增加它.帮我找到更好的解决方案?

编辑:好的,请忽略上述内容.我已经得到了相当不错的答案,但让我感到惊讶的是,几乎没有关于角色扮演游戏库存系统的教程.我做了很多谷歌搜索,找不到任何好的例子/教程/源代码.如果有人能指出一些好的例子/教程/源代码(无论什么语言,但更好的java,甚至是c/c ++),我将不胜感激,谢谢.哦,还有关于这个主题的任何书籍.

aio*_*obe 22

解决此问题的常用方法(使用标准API)是使用Map<Item, Integer>将项目映射到清单中此类项目的数量.

获得某个项目的"金额",您只需致电get:

inventory.get(item)
Run Code Online (Sandbox Code Playgroud)

要为您的库存添加内容

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

inventory.put(item, inventory.get(item) + 1);
Run Code Online (Sandbox Code Playgroud)

例如,要从库存中删除某些内容

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);
Run Code Online (Sandbox Code Playgroud)

如果你在很多地方这样做,这可能会变得混乱,所以我建议你将这些方法封装在一个Inventory类中.

祝好运!


Pet*_*rey 6

与aioobe的解决方案类似,您可以使用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);
Run Code Online (Sandbox Code Playgroud)

您可以创建一个倍数类.

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

List bag = new ArrayList();
bag.add(new Sword());
bag.add(new MultipleOf(5, new Potion());
Run Code Online (Sandbox Code Playgroud)

或者您可以使用按次数记录倍数的集合.

例如一个

Bag bag = new HashBag() or TreeBag();
bag.add(new Sword());
bag.add(new Potion(), 5);
int count = bag.getCount(new Potion());
Run Code Online (Sandbox Code Playgroud)


Fly*_*179 5

你可能最好InventorySlot用一个数量和内容字段创建一个名为的类.这也使您可以灵活地添加其他属性,例如库存槽可以包含的内容,如果您决定仅创建"药水"袋或类似的东西.

或者,在很多MMO中使用a StackCount和boolean IsStackable,或者也许MaxStack属性,它也是一种非常有效的技术.