summaryrefslogtreecommitdiff
path: root/npc/functions/RNGesus.txt
blob: a5fe54eb48ca837527e177bc8a789d6d47a6d042 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Evol functions.
// Authors:
//    gumi
// Description:
//    Randomization helper functions.



// any(<arg>{, ...<arg>})
//     returns one argument randomly

function	script	any	{
    return getarg(rand(getargcount()));
}



// any_of(<array>)
//     returns any member of the array

function	script	any_of	{
    return getelementofarray(getarg(0), getarrayindex(getarg(0)) + rand(getarraysize(getarg(0)) - getarrayindex(getarg(0))));
}



// relative_array_random(<array: 0, {[value, probability]..}>)
//     returns a random entry from the array, by relative probability
//     the first key of the array should be 0 and every entries are a tuple
//     of [value, probability]

function	script	relative_array_random	{
    .@total_prob = getelementofarray(getarg(0), 0);
    .@initial_index = getarrayindex(getarg(0));
    .@initial_index = .@initial_index ? .@initial_index : 1;
    freeloop(true);

    if (.@total_prob < 1 || getarg(1, false))
    {
        // first calculation, or forced re-calculation
        .@total_prob = 0;
        .@size = getarraysize(getarg(0));

        for (.@i = .@initial_index + 1; .@i < .@size; .@i += 2)
            .@total_prob += getelementofarray(getarg(0), .@i);

        // we cache on the first key
        set(getelementofarray(getarg(0), 0), .@total_prob);
    }

    .@target_sum = rand(.@total_prob);

    for (.@i = .@initial_index; .@sum < .@target_sum; .@i += 2)
        .@sum += getelementofarray(getarg(0), .@i + 1);

    freeloop(false);
    return getelementofarray(getarg(0), max(0, .@i - 2));
}