问题
I am building a Terraria like game and I am having a problem with where to store the recipes..
basically what my game should do is go through the player inventory (which is an array of id's) and check recipe by recipe if all the item's are in the player inventory.
I dont know how to store the recipes and how to handle them, i though of using array but the size of the array vary from item to item, I though of list too but it is a lot of writing and I want a "clean" code.
what should i use to store my recipes?
and if you suggest me to use array, should i make it static and declare every recipe and my "Crafting" class?
thanks.
(The recipe's should be id's and the amount per id)
回答1:
I've never played Terraria, but it sounds like a pretty simple LINQ query:
If your recipe object contains a List of InventoryItem
:
struct InventoryItem
{
int itemId;
int itemCount;
}
class Recipe
{
String name;
List<InventoryItem> RequiredItems { get; set; }
}
And your inventory is a list of the same structure, then its just:
bool canUseRecipe = recipe.RequiredItems.All(i =>
{
InventoryItem itemInInventory = Inventory.FirstOrDefault(x => x.itemId == i.itemId);
return itemInInventory == null ? false : itemInInventory.itemCount >= i.itemCount;
});
There might be a way to collapse that into a one liner, but this is probably more clear!
You could also seperate it out into a different function:
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;
});
来源:https://stackoverflow.com/questions/23434025/how-to-store-and-handle-ingame-recipes