Page 1 of 1

Random Generator?

PostPosted: Wed Nov 08, 2006 2:38 pm
by regine
How to make an random generator?

PostPosted: Wed Nov 08, 2006 5:23 pm
by sonicfire
can you be a bit more precise?

PostPosted: Thu Nov 09, 2006 1:58 am
by Fuzzy
int seed = 1000;
int srand(int low, int high)
{
seed = ((104723*seed)+104729)%2147483647;
return abs(seed %(high-low)+low);
}

is a really simple one. seed is whatever you want to start with(its just a number). after you call the function, seed becomes equal to the last value it generated(but not the random number you ask for). Leave seed alone after you set it the first time.

104723 and 104729 are PRIME numbers. Google can help you get a list if you want to change them. Both of those numbers MUST be primes, so the sequence doesnt repeat quickly.

2147483647 is is the maximum positive integer. Leave that as it is.

high and low are integers that you set; they are your high and low values.

put the global var and the function in global code.
You use it like this in an actor script:

health = srand(0, 100);


This is a deterministic Random function. it will output the exact same sequence of numbers each time. To change that sequence, change the seed. Why would anyone want to do this?

Say you had a bad guy called "bad pants Vance" instead of saving 30 numbers for Vances stats, you would save his name to file, and a seed.
Now when you load Vance, in his create actor event, Set the seed to Vances seed, and use srand to set the stats. They will always be the same.

This is useful for having a game with 1000 unique monsters, without needing 10s of megabytes of storage, or creating endless universes of planets.

PostPosted: Thu Nov 09, 2006 9:05 am
by DilloDude
Here's one I wrote:
Code: Select all
#define USE_LAST_SEED -1
#define USE_NEXT_SEED 0
double seedrand(int seed, double maxsize)
{
    static int retval;
    double final;
 
    switch(seed)
    {
        case -1:
        break;
 
        case 0:
        seed = retval;
 
        default:
        seed = abs(seed);
        retval = abs(fmod(seed * 16807, 2147483647));
        break;
    }
    final = (round(retval) / 2147483647) * maxsize;
    return  final;
}

It's basically the same, only you don't put in a minimum (you have to add it afterwards) and you put the seed as a function parameter. You can put the seed as USE_NEXT_SEED to generate the next number in the sequence, or USE_LAST_SEED to use the seed from the last time seedrand was called.
For more info look at http://www.math.utah.edu/~pa/Random/Random.html