[英]Searching for child class properties in a list
现在我正在创建一个 Quest Requirement Checker,以查看玩家是否能够完成任务。 我现在正在处理的任务类型是“在库存中有一件物品”,如您所见,如果玩家在他/她的库存中有一个或多个指定的物品,就会完成。
现在,我的确切问题是什么? 嗯,……物品。
首先。 Item
是一个具有下一个结构的类:
public int ID { get; set; }
public string Name { get; set; }
public double Price { get; set; }
public Item(int id, string name, double price)
{
ID = id;
Name = name;
Price = price;
}
还有一个名为Tool
的类,它扩展了Item
类:
public string Material { get; set; }
public string Classification { get; set; }
public Tool
(
int id,
string name,
double price,
string material,
string classification
) : base(id, name, price)
{
Material = material;
Classification = classification;
}
现在,这就是我创建每个工具的方式:
Items.Tool tool = new Items.Tool(1, "Shovel", 100, "Wood", "Poor");
我的播放器对象有这样的项目列表:
public List<Items.Item> InventoryItems { get; set; }
它作为它的库存。 此外,要向列表中添加新项目,我使用此函数:
player.AddItem(tool, 1);
public void AddItem(Items.Item item, int quantity)
{
for(int i = 0; i < quantity; i++)
{
InventoryItems.Add(item);
}
}
另一方面,我当前的任务类型“库存中有物品”有一个属性,同时也是一个物品列表:
public List<Items.Item> RequiredItems { get; set; }
这就是我向此列表添加项目的方式:
quest.AddRequiredItem(tool, 1);
public void AddRequiredItem(Items.Item item, int quantity)
{
for(int i = 0; i < quantity; i++)
{
RequiredItems.Add(item);
}
}
为了完成这个任务,玩家必须拥有与RequiredItems
列表相同数量(或更多)的物品。 所以,如果这个任务要求玩家四处寻找 3 个劣质木铲,它的InventoryItems
列表中应该至少有 3 个劣质木铲。
我的任务是一个名为HaveItemsInInventory
的类,它实现了下一个函数以评估该条件:
override public bool Accomplish()
{
bool questAccomplished = true;
foreach (var group in RequiredItems.GroupBy(x => x))
{
if (Application._player.InventoryItems.Count
(
x =>
(
x.Name == group.Key.Name &&
x.Material == group.Key.Material &&
x.Classification == group.Key.Classification
)
) < group.Count())
{
questAccomplished = false;
break;
}
}
return questAccomplished;
}
这就是我所有问题出现的地方。 这两行或代码是错误的:
x.Material == group.Key.Material &&
x.Classification == group.Key.Classification
因为在Item
没有Material
或Classification
之类的东西。
我想做的是实施不同类型的评估。
如果任务要求一杯水,我应该寻找住在我的Beberage
班级内的财产。
如果任务只要求一把剑。 我应该在其库存中寻找名称为“Sword”的物品。
如果任务要求钻石传奇剑,那么......你明白我的意思。
有没有办法在我的系统中查找这些扩展类属性? 我找不到这样做的方法。
PD:对不起,我的英语不好,不是母语人士。
编辑:我已经编辑了我的答案以解决通用任务方法的想法。
如果您希望任务能够跨多种不同类型的通用的,你可能想实现一个IsSame
或IsEquivalent
的方法Items.Item
,然后继承该方法。 您甚至可以覆盖 Object.Equals 方法(这可能是更合适的方法)。
class Item
{
public virtual bool IsSame(Item comp){ return comp.Name == Name; }
}
class Tool: Item
{
public override bool IsSame(Item comp)
{
return base.IsSame(comp) && (comp is Tool) && ((Tool)comp).Material == Material && ((Tool)comp).Classification == Classification;
}
}
然后在你的完成迭代中:
override public bool Accomplish()
{
bool questAccomplished = true;
foreach (var group in RequiredItems.GroupBy(x => x))
{
if (Application._player.InventoryItems.Count
(
x =>
(
x.IsSame(group.Key)
)
) < group.Count())
{
questAccomplished = false;
break;
}
}
return questAccomplished;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.