Welcome!

Think Labs is an ongoing effort by Seven2 to provide research and educational opportunities in the web development and mobile field. To see what we’ve been cookin’ up, check out our blog postings.

Created by
Seven2 Login

Categories
Tags
Team Think Labs | Grabbing Items From an Array Based on Probability
66
single,single-post,postid-66,single-format-standard,ajax_fade,page_not_loaded,,,wpb-js-composer js-comp-ver-4.2.3,vc_responsive

Grabbing Items From an Array Based on Probability

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.

Because this is such a common scenario I run into, I wanted to make a class to automate this process. After a lot of googling (and many false starts) I finally came up with something that looked close to what I wanted to do. The result is the WeightedRandomPool class. I’ve created ActionScript and Javascript versions of this code, so hopefully you find this useful.

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:

chestItems.changeWeight("poison", 100);

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.

The api for the javascript version is exactly the same. Below are both versions.

I hope this class helps you out in your Flash and JavaScript projects. Enjoy!

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.