c# - 从通用项目工厂返回的随机项目(加权)
问题描述
我目前正在尝试编写一个小游戏的项目工厂类有问题。我目前正在做的事情如下:
- 我有一个列表,其中包含我所有可能的类型 x 游戏项目(盔甲,武器,...),基类类型为 Item
- 每个项目都有一个来自稀有枚举的稀有度(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 字典中的稀有百分比。
有人对如何以我的编码方式解决此类任务有任何想法或建议吗?
先感谢您!
解决方案
像这样的东西可能会起作用:
// Assuming this is the type
Dictionary<Rarity, int> _actualRarityPercentages;
public IEnumerable<T> GetRandomItem<T>(int count = 1, Rarity maxRarity = Rarity.Common, List<int> ids = null)
where T : Item
{
InitializeActualRarities(maxRarity);
int maxRarityValue = _actualRarityPercentages[maxRarity];
return GetItems<T>().ToList()
.Where(item => _actualRarityPercentages[item.Rarity] <= maxRarityValue)
.Clone()
.PickRandom(count)
}
我假设这_actualRarityPercentages
是一个简单的字典 from Rarity
to int
。使用LINQWhere
,您应该能够过滤比maxRarity
.
希望有帮助
推荐阅读
- flask - FLASK AZURE SQL DB - 查询运行非常缓慢
- mysql - 如何获取不同项目的最新计数(基于日期)?
- java - 新手在 Java 中使用缓存 API 的最佳方式
- php - 在弹性搜索中按 ID 自定义排序顺序作为数组
- c++ - 使用 boost 从 json 读取缓冲区
- solver - MiniZinc int 超出范围
- javascript - 无效的 useSelector 挂钩调用
- fantom - 为什么从我的合同中撤销 FTM 失败?
- python - 如何单击python-selenium中具有相同名称的按钮
- c++ - 比许多嵌套的“for”循环更好的东西?