首页 > 解决方案 > 从通用项目工厂返回的随机项目(加权)

问题描述

我目前正在尝试编写一个小游戏的项目工厂类有问题。我目前正在做的事情如下:

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);
}
    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 字典中的稀有百分比。

有人对如何以我的编码方式解决此类任务有任何想法或建议吗?

先感谢您!

标签: c#linqrandom

解决方案


像这样的东西可能会起作用:

// 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 Rarityto int。使用LINQWhere,您应该能够过滤比maxRarity.

希望有帮助


推荐阅读