我正在建造一个类似Terraria的游戏,我在哪里存放食谱时遇到了问题..
基本上我的游戏应该做的是浏览玩家库存(这是一系列id),如果所有项目都在玩家库存中,则按食谱检查食谱。
我不知道如何存储食谱以及如何处理它们,我虽然使用数组,但数组的大小因项目而异,我虽然列表也是如此,但它是大量的写作,我想要一个"清洁"代码。
我应该用什么来储存我的食谱?
如果你建议我使用数组,我应该让它静态并声明每个食谱和我的" Crafting"类?
感谢。
(食谱应该是id' s和每个ID的数量)
答案 0 :(得分:1)
我从未玩过Terraria,但这听起来像一个非常简单的LINQ查询:
如果您的配方对象包含InventoryItem
的列表:
struct InventoryItem
{
int itemId;
int itemCount;
}
class Recipe
{
String name;
List<InventoryItem> RequiredItems { get; set; }
}
您的库存是一个相同结构的列表,然后只是:
bool canUseRecipe = recipe.RequiredItems.All(i =>
{
InventoryItem itemInInventory = Inventory.FirstOrDefault(x => x.itemId == i.itemId);
return itemInInventory == null ? false : itemInInventory.itemCount >= i.itemCount;
});
可能有办法将其折叠成一个班轮,但这可能更清楚了!
您也可以将其分成不同的功能:
bool canUseRecipe = recipe.RequiredItems.All(i => SufficientItemsInInventory(i));
//Or
bool canUseRecipe = recipe.RequiredItems.All(SufficientItemsInInventory);
...
private bool SufficentItemsInInventory(InventoryItem item)
{
InventoryItem itemInInventory = Inventory.FirstOrDefault(i => i.itemId == item.itemId);
return itemInInventory == null ? false : itemInInventory.itemCount >= i.itemCount;
});