If the method was going to be used alot, then I would definitely go with a similar approach to yours where a class handles all the chance calculations and rewards etc.Quote:
if there are few cases, you could code it in a switch statment, for example
int n = random.Next(3);
switch(n)
{
case 1: //50% {..}
case 2: //50% {...}
}
just noticed that Ace gave you a better example :p
if you got a bigger list of items with their drop chance you could write a simple class to handle those chances by you and then load them, just wrote this
note that in the class the probability of get one object is based on the amount of cases, for example, if you addCode:public class ProbabilityManager<T> { private SafeRandom random; private SortedDictionary<int, T> probabilitiesPool; private int amountOfCases; public ProbabilityManager() { amountOfCases = 0; random = new SafeRandom(); probabilitiesPool = new SortedDictionary<int, T>(); } public void Add(T TObject, int probability) { amountOfCases += probability * 100; probabilitiesPool.Add(amountOfCases, TObject); } public bool Get(out T value) { int seed = random.Next(amountOfCases + 1); int accumulativeIndex = 0; value = default(T); for (int i = 0; i < probabilitiesPool.Count; i++) { var elementAtIndex = probabilitiesPool.ElementAt(i); accumulativeIndex += elementAtIndex.Key; if (elementAtIndex.Key >= seed) { value = elementAtIndex.Value; return true; } } return false; } }
Add(T1, 2);
Add(T2, 3);
~60% of times that you use Get() you will get T2, and ~40% T1
you could create a new method to add "empty chance" so for example a mob could drop one of 4 items or none of them, i was lazy to code that
But for an item or two, I think a simple if/else if structure works just fine.