Ok so it’s not the snappiest title, but something that comes in extremely handy!
Part of making games more fun is introducing an element of randomness. If you’re making a dungeon crawler, you may want to specify different surprise items in a treasure chest. To make the chances equally random can be boring, because most of the time you want the chest to contain good items and only rarely do you want it to spew toxic gas.
How to Use:
If we were going to use the above treasure chest example, I might store different strings with the names of possible items in the chest.
var chestItems:WeightedRandomPool = new WeightedRandomPool(); chestItems.add("gold", 10); chestItems.add("jewels", 10); chestItems.add("poodles", 2); chestItems.add("poison", 1); // Gets an item from the pool. var sRandomItem:String = chestItems.get();
So in the above example, we have “gold” and “jewels” both with a weight of 10, and “poodles” and “poison” with much lower weights. The weights are all relative to each other. All of them must be positive integers larger than 0.
In the example above, the “gold” and “jewels” are both 10 times more likely to be selected than “poison,” and 5 times more likely to be selected than “poodles.”
Let’s say that in your game you had a curse put on you, and you want to make it much more likely that “poison” will be in the chests. With one line, you can make that happen:
Now since the highest weight is 100, “poison” is 10 times more likely to be selected than “jewels” or “gold.” Sadly for the poodles, they would be 50 times less likely to be selected than poison.
p.s. A special thanks goes out to ‘stephj’ of XDA-Developers forum for the code I blatantly
ripped off adapted. The original post can be found here.