【发布时间】:2019-07-18 14:53:55
【问题描述】:
我目前正在尝试编写一个小游戏的项目工厂类有问题。我目前正在做的事情如下:
- 我有一个列表,其中包含我所有可能的类型 x 的游戏项目(盔甲、武器……),基类类型为 Item
- 每个项目都有一个来自 rarity 枚举的稀有度(0 = 常见,1 = 不常见,依此类推)
- 实际稀有度“生成”百分比保存在包含稀有度和百分比的字典中
- 目前我有一个通用方法返回随机项的新实例:
public IEnumerable<T> GetRandomItem<T>(int count = 1, Rarity maxRarity = Rarity.Common, List<int> ids = null)
where T : Item
{
InitializeActualRarities(maxRarity);
return GetItems<T>().ToList().Where(i => CheckItemConditions(ref i, maxRarity, ids)).Clone().PickRandom(count);
}
GetRandomItem 方法返回的项目始终是(a)从项目列表中随机选取的对象的副本。
InitializeActualRarities 方法为低于最大稀有度的所有稀有度生成百分比:
private void InitializeActualRarities(Rarity maxRarity)
{
_actualRarityPercentages.Clear();
var remaining = 100;
Enum.GetValues(typeof(Rarity)).OfType<Rarity>().Where(r => _staticRarityPercentages[r] >= _staticRarityPercentages[maxRarity]).ToList().ForEach(r =>
{
remaining -= _staticRarityPercentages[r];
_actualRarityPercentages.Add(r, _staticRarityPercentages[r]);
});
var key = _actualRarityPercentages.Aggregate((l, r) => l.Value > r.Value ? l : r).Key;
_actualRarityPercentages[key] += remaining;
}
目前我显然没有在我的 GetRandomItem 方法中使用实际的稀有百分比,而这正是我想要改变的。
我想以某种方式调整 linq,以确保仅返回给定最大稀有度的项目以及 _actualRarityPercentages 字典中的稀有百分比。
有人对如何以我的编码方式解决此类任务有想法或建议吗?
提前谢谢你!
【问题讨论】: