【问题标题】:Returned random item (weighted) from generic item factory [duplicate]从通用项目工厂返回随机项目(加权)[重复]
【发布时间】: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 字典中的稀有百分比。

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

提前谢谢你!

【问题讨论】:

    标签: c# linq random


    【解决方案1】:

    这样的事情可能会奏效:

    // 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 是从Rarityint 的简单字典。使用LINQ Where,您应该能够过滤比maxRarity 更稀有的项目。

    希望有帮助

    【讨论】:

    • 这将有助于确保正确的稀有性被退回。实际上已经是这种情况,因为我正在 CheckItemCondition 调用中进行此检查。我需要的只是加权选择,而不仅仅是选择。
    【解决方案2】:

    尝试以下:

    public IEnumerable<T> GetRandomItem<T>(int count = 1, Rarity maxRarity = Rarity.Common, List<int> ids = null)
      where T : Item
    {
      InitializeActualRarities(maxRarity);
      Random rand = new Rand();
      return GetItems<T>().ToList().Where(i => CheckItemConditions(ref i, maxRarity, ids)).Clone().Select((x,i) => new {item = x, rand = rand.Next()}).OrderBy(x => x.rand).Select(x => x.item).Take(count);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-24
      • 2010-09-28
      • 1970-01-01
      • 2012-06-10
      • 1970-01-01
      • 2020-11-02
      • 2011-11-14
      • 1970-01-01
      相关资源
      最近更新 更多