C#工艺逻辑
本文关键字: | 更新日期: 2023-09-27 17:59:26
有很多类似的问题,但没有一个有明确答案。我正在使用Unity3D引擎来创建一个游戏。我已经建立了一个库存系统,其中包括添加项目、删除项目和检查库存是否包含一定数量的项目的方法。
我想做的是在每次更新时,循环浏览物品,如果玩家有制作食谱所需的物品,则在列表中显示添加按钮,玩家可以点击该按钮来制作新物品。
我想我可以用字典来存储所需的项目和数量。类似这样的东西:
public static Dictionary<string, int> sword = new Dictionary<string, int>() {
{"stone", 2},
{"Wood", 1}
};
public static Dictionary<string, int> plank = new Dictionary<string, int>() {
{"Wood", 5}
};
但我也需要一种方法来存储所有的食谱并循环使用它们。就像一本字典。这样我就可以循环浏览所有手工制作的物品名称。我能做一些类似的事情吗?
public static Dictionary<string, Dictionary> recipes = new Dictionary<string, int>() {
{"Wood Sword", sword},
{"Wood Plank", plank}
};
我希望能够在一个类文件中定义所有的食谱,并在另一个类中循环使用它们。
我对c#没有太多的经验,所以我不太擅长使用列表和字典,所以如果有任何建议和帮助,我将不胜感激。
谢谢!
嗯。。根据你的规格,我想出了这样的东西:
public enum Ingredient = { Wood, Stone, Water, Gold/*and so on*/ };
public class RecipeItem
{
public Ingredient Ingredient{ get; set;}
public int Amount {get; set;}
}
public class Recipe
{
public string Name {get; set;}
public List<RecipeItem> RecipeItems {get;set;}
}
定义配方时,代码中的某个位置:
var recipes = new List<Recipe>(){
new Recipe(){
Name = "Wood Sword",
RecipeItems = new List<RecipeItem>(){
new RecipeItem(){
Ingredient = Wood,
Amount = 1
},
new RecipeItem(){
Ingredient = Stone,
Amount = 5
}
}
},
new Recipe(){
Name = "Plank",
RecipeItems = new List<RecipeItem>(){
new RecipeItem(){
Ingredient = Wood,
Amount = 5
}
}
}
// More recipes
};
附言:我建议你花几天时间学习C#的基础知识
您要查找的是类似Dictionary<string, Dictionary<string, int>>
的东西——一个具有string
键和Dictionary<string, int>
值的Dictionary
。初始化如下:
var recipes = new Dictionary<string, Dictionary<string, int>>
{
{ "Sword", new Dictionary<string, int> { { "stone", 2 }, { "wood", 1 } } },
{ "Plank", new Dictionary<string, int> { { "wood", 5 } } }
};
就我个人而言,我觉得这有点沉重,很容易处理。我更倾向于使用一种结构来固定内部,比如:
public struct RecipeComponent
{
public readonly string Material;
public readonly int Count;
public RecipeComponent(string material, int count)
{
Material = material;
Count = count;
}
}
public readonly Dictionary<string, RecipeComponent[]> recipes = new Dictionary<string, RecipeComponent[]>
{
{ "Sword", new[] { new RecipeComponent("stone", 2), new RecipeComponent("Wood", 1) } },
{ "Plank", new[] { new RecipeComponent("Wood", 5) } }
};
稍微更健壮一些,但您仍然可以在运行时操作recipes
列表的内容,包括替换所需组件的列表。ReadOnlyDictionary
有助于解决这个问题。
到目前为止(对我来说),最简单的方法是使用泛型列表和for循环。第一:使用此功能检查物品是否在库存中public bool CheckItems(列表检查){
List<Item> it = new List<Item> (check);// Make sure original list is not changed.
foreach(Item inventoryItem in myItems) {// Loop through your INVENTORY's items.
if (it.Contains(inventoryItem)) {//If contains, remove.
it.Remove(inventoryItem);
if(it.Count == 0) {
return true; //When the count is less than zero, you can craft the item.
}
}
}
return false;
}
这只需要在craft函数中调用,如果返回true,则可以制作物品。注意:检查列表是工艺所需物品的列表,myItems是库存物品的列表。