安卓游戏RPG库存系统

8
我正在使用一个ArrayList作为我的“库存”。 我遇到了一个问题,想要在不占用“库存”中的位置的情况下添加多个相同的物品。例如:我将一瓶药水添加到我的库存中。现在,我再次添加一瓶药水,但这次它应该显示我有:药水 x 2,同时只占用ArrayList中的一个位置。我想出了一些解决方案,但感觉它们都是不好的做法。我尝试过的一个解决方案是向物品本身添加一个AMOUNT变量并增加它。帮我找到一个更好的解决方案好吗?
编辑:好吧,请忽略上面那个问题。我已经得到了很好的答案,但令我惊讶的是,几乎没有角色扮演游戏库存系统的教程。我做了很多谷歌搜索,找不到任何好的示例/教程/源代码。如果有人可以指点我一些好的示例/教程/源代码(不管什么语言,但最好是Java,甚至C / C ++),我会很感激的,谢谢。哦,还有任何关于这个主题的书籍。

查看这个不错的开源游戏 http://www.epiar.net/ - Sherif elKhatib
这是一个有趣的问题。最好使用的数据结构将取决于许多设计问题,例如可能的项目数量是小而有限还是非常大,是否存在插槽容量或物品或重量容量,它是自动排序还是由玩家排序,游戏代码的其余部分需要执行什么类型的查询等等... - avh4
5个回答

22
通常解决这个问题的方法(使用标准API)是使用一个Map<Item,Integer>将物品映射到库存中该物品的数量。
要获取特定物品的“数量”,则只需调用get
inventory.get(item)

要将某物品添加到库存中,您需要执行以下操作:
if (!inventory.containsKey(item))
    inventory.put(item, 0);

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

从库存中删除某物,你可以执行以下操作:
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);

如果在多个地方这样做,可能会变得混乱不堪,因此我建议您将这些方法封装在一个 Inventory 类中。

祝你好运!


我对这个想法不太确定;当然,这取决于库存的表示方式,但这意味着您只能拥有每种物品类型的一个堆栈。如果有任何关于库存“插槽”的概念,这将无法实现。 - Flynn1179
啊哈,没错。那么人们可能会为堆栈添加一个中间的List。但是数据结构开始变得复杂了,所以我可能会在这里某个地方将其分解为一个类。 - aioobe
+1:我会将添加计数写成 int add = ...; Integer count = inventory.get(item); if (count == null) inventory.put(item, add); else inventory.put(item, count + add); - Peter Lawrey

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);

你可以创建一个多类。
class MultipleOf<T> {
    int count;
    final T t;
}

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

你可以使用一个记录数量的集合来记录多个内容。
例如,一个袋子
Bag bag = new HashBag() or TreeBag();
bag.add(new Sword());
bag.add(new Potion(), 5);
int count = bag.getCount(new Potion());

我不熟悉多重类。这些有什么用途? - semajhan
如果您想要更新计数或轻松查找数量,您需要包装列表。例如: - Peter Lawrey

5
您最好创建一个名为 InventorySlot 的类,其中包括数量和内容字段。这样做还可以让您具有添加其他属性的灵活性,例如,如果您决定创建一个“药水”专用袋之类的东西,则可以确定库存槽可以包含什么。
或者,在不少 MMO 中使用了 StackCount 和布尔型 IsStackable,或者也可以使用 MaxStack 属性,这也是完全有效的技术手段。

2

或者一个InventoryField类,其中包含一个物品和一个表示数量的整数。

public class InventoryField{
    int count;
    Item item;
}

public class Inventory extends ArrayList<InventoryField>{
       ...
    }

-2
以下是一个示例: public class Item{ int count; String name; }
然后创建一个代表库存的列表: public class Player { List inventory = new ArrayList(); }

OP说他已经尝试在项目中有一个AMMOUNT变量。 - aioobe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接