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.


一様でないランダムな選択を行う

数学的な説明をすれば、それぞれの確率が与えられたリスト中のデータから値を1つ抽出する、非一様確率分布をもつランダム関数を実装します。

以下にキス音のリストがあり、ランダムに選びたいとします。 しかし、kiss3.mp3は特別な音なので、その他のキス音より選ばれにくくしたい場合はどうすればよいでしょう。

タプルのリストによる方法

選択肢のリストを作成し、それぞれにどれぐらいの頻度で選ばれるかの重みを指定します:

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

上記のリストの場合、7回中 kiss.mp3 が3回、kiss2.mp3 が3回、kiss3.mp3 が1回の確率で選ばれるようにします。

コード

Pythonを用いて実装します。

python:
       class NonUniformRandom(object):
            def __init__(self, list_of_values_and_probabilities):
                """
                値と確率のリスト [ (値, 確率), (値, 確率), ...]
                """
                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):
                """
                決められた確率に従ってランダムな値を返す
                """
                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

コードの使用例

python:
    # 選ばれる結果とその発生頻度を指定して初期化
    n = NonUniformRandom( [('kiss1.mp3', 3), ('kiss2.mp3',3), ('kiss3.mp3',1)] )
    # キス音を14回再生する
    for i in range(14):
        renpy.sound.queue(n.pick())