Add item rarity management and random item generation logic

This commit is contained in:
Jose Henrique 2025-02-02 12:42:52 -03:00
parent 0a257199f7
commit c433095eb8

View File

@ -7,9 +7,15 @@ namespace Pet.Companion.Repositories
public class ItemRepository
{
private readonly Dictionary<string, Item> _itemTemplates = new();
private readonly Dictionary<ItemRarity, List<string>> _itemsByRarity = new();
private readonly Random _random = new();
public ItemRepository()
{
foreach (ItemRarity rarity in Enum.GetValues(typeof(ItemRarity)))
{
_itemsByRarity[rarity] = new List<string>();
}
LoadItemsFromCsv();
}
@ -33,6 +39,7 @@ namespace Pet.Companion.Repositories
};
_itemTemplates.Add(name, item);
_itemsByRarity[rarity].Add(name);
}
}
@ -117,5 +124,53 @@ namespace Pet.Companion.Repositories
throw new KeyNotFoundException($"Item template not found: {itemName}");
}
/// Usage:
/* var rarityProbabilities = new Dictionary<ItemRarity, int>
{
{ ItemRarity.Common, 50 }, // 50% chance
{ ItemRarity.Uncommon, 30 }, // 30% chance
{ ItemRarity.Rare, 15 }, // 15% chance
{ ItemRarity.Legendary, 5 } // 5% chance
};
var itemRepo = new ItemRepository();
var randomItem = itemRepo.GenerateRandomItem(rarityProbabilities);
*/
public Item GenerateRandomItem(Dictionary<ItemRarity, int> rarityProbabilities)
{
// Validate probabilities
if (rarityProbabilities.Values.Sum() != 100)
{
throw new ArgumentException("Rarity probabilities must sum to 100");
}
// Generate random number between 0 and 100
var roll = _random.Next(1, 101);
var currentThreshold = 0;
// Determine which rarity we hit
ItemRarity selectedRarity = ItemRarity.Common;
foreach (var probability in rarityProbabilities)
{
currentThreshold += probability.Value;
if (roll <= currentThreshold)
{
selectedRarity = probability.Key;
break;
}
}
// Get random item from selected rarity
var possibleItems = _itemsByRarity[selectedRarity];
if (possibleItems.Count == 0)
{
// Fallback to common if no items of selected rarity
possibleItems = _itemsByRarity[ItemRarity.Common];
}
var randomItemName = possibleItems[_random.Next(possibleItems.Count)];
return CreateItem(randomItemName);
}
}
}