Пример #1
0
    /// <summary>
    /// Returns a random Item
    /// </summary>
    /// <param name="focus">You can Focus on a Item to have a higher chance to get this</param>
    /// <returns></returns>
    InventoryItem_Base getRandomItem(FocusType focus = FocusType.None)
    {
        FocusType foundItemType = FocusType.None;
        List <Dictionary <FocusType, int> > dictList = new List <Dictionary <FocusType, int> >();

        // Fill list with dictionaries of FocusType and standardItemTypeProbability
        foreach (FocusType item in Enum.GetValues(typeof(FocusType)))
        {
            dictList.Add(new Dictionary <FocusType, int> {
                { item, standardItemTypeProbability }
            });
        }

        dictList.Remove(dictList.Single(x => x.Keys.First() == FocusType.None));

        int totalItemTypeProbability = 0;

        // Add additional focus probability and calculate totalItemTypeProbability
        foreach (var dict in dictList)
        {
            if (focus != FocusType.None)
            {
                if (dict.ContainsKey(focus))
                {
                    dict[focus] += addedFocusProbability;
                }
            }

            totalItemTypeProbability += dict.Sum(x => x.Value);
        }

        System.Random r            = new System.Random();
        var           randomNumber = r.NextDouble() * totalItemTypeProbability;
        double        totalSoFar   = 0;

        // Calculate foundItemType based on related probabilities
        foreach (var item in dictList)
        {
            totalSoFar += item.Sum(x => x.Value);
            if (totalSoFar > randomNumber)
            {
                foundItemType = item.Keys.First();
                break;
            }
        }
        Debug.Log("foundItemType: " + foundItemType.ToString());

        List <InventoryItem_Base> newList = new List <InventoryItem_Base>(Inventory.Instance.AvailableItems);

        // Filter list to only contain the specific item type based on the prior calculated foundItemType
        newList = newList.Where(i => i.GetType().Name.Contains(foundItemType.ToString())).ToList();

        Debug.Log("newList:");
        newList.ForEach(x => Debug.Log(x.Name));

        int totalItemRarity = newList.Sum(x => x.Rarity);

        System.Random rand             = new System.Random();
        var           randomItemNumber = rand.NextDouble() * totalItemRarity;

        totalSoFar = 0;

        // Calculate found item based on related Rarity
        foreach (var item in newList)
        {
            totalSoFar += item.Rarity;
            if (totalSoFar > randomItemNumber)
            {
                Debug.Log("found item: " + item.Name);
                return(item);
            }
        }

        return(null);
    }