This page is out of date

You've reached a page on the Ren'Py wiki. Due to massive spam, the wiki hasn't been updated in over 5 years, and much of the information here is very out of date. We've kept it because some of it is of historic interest, but all the information relevant to modern versions of Ren'Py has been moved elsewhere.

Some places to look are:

Please do not create new links to this page.


Making random choices with some outcomes more likely than others

A more technical way to describe this would be a random choice with discrete non-uniform probability distribution.

Suppose you have the following list of kissing sounds, and you want to pick one at random. But because kiss3.mp3 is a very special kissing sound, you want it to be chosen less often than the other kissing sounds. How do you go about this?

The input

We will start from a list of possible options, and to each item we give a "weight" that says how likely it is to be chosen:

[('kiss1.mp3',3) , ('kiss2.mp3',3) , ('kiss3.mp3',1)]

The above list would mean that out of 7 times, on average, 3 times kiss1.mp3 should be chosen, 3 times kiss2.mp3 should be chosen and only one time kiss3.mp3 should be chosen.

The code

This requires some python code.

python:
       class NonUniformRandom(object):
            def __init__(self, list_of_values_and_probabilities):
                """
                expects a list of [ (value, probability), (value, probability),...]
                """
                self.the_list = list_of_values_and_probabilities
                self.the_sum = sum([ v[1] for v in list_of_values_and_probabilities])

            def pick(self):
                """
                return a random value taking into account the probabilities
                """
                import random
                r = random.uniform(0, self.the_sum)
                s = 0.0
                for k, w in self.the_list:
                    s += w
                    if r < s: return k
                return k

Example using this code

python:
    # initialize our random picker with the options and their likelyhood of being selected:
    n = NonUniformRandom( [('kiss1.mp3', 3), ('kiss2.mp3',3), ('kiss3.mp3',1)] )
    # Now generate a kissing demonstration with 14 kissing sounds
    for i in range(14):
        renpy.sound.queue(n.pick())