## How to make a script happen randomly?

### How to make a script happen randomly?

How do I make a script that goes on a chance, such as there is a 1/10 random chance for this script function to happen? Any help would do, thank you.
Disclaimer: I don't actually love goats (that much, mind). :P

WeLuvGoatz

Posts: 228
Joined: 23 May 2018, 19:15

### Re: How to make a script happen randomly?

SuperTux uses the Squirrel scripting language. The basic syntax guide is here and the standard API guide is here. I have never used it, so the size of the language caught me off guard a bit.

The API has this function:

rand();

returns a pseudorandom integer in the range 0 to RAND_MAX

The standard (though not necessarily best) way of dealing with integer random number generators is to use the modulo operator ( % ) which causes numbers to wrap around. It is the integer-only counterpart to the fmod function in C.

MyRandomNumber = rand() % 10

^ MyRandomNumber is a pseudorandom number in the range 0 - 9 inclusive, because if rand() returns 10, the % causes it to be subtracted and wrap back to 0, a sort of circular number thing which is mathematically useful for angles (at least in fmod form; dunno if Squirrel has an fmod function).

The only time this will cause you problems is when you are using really small integers (generally less than 10) and even distribution/probability is important, because random number generators often have rather coarse precision and poor distribution, resulting in (for instance) a lot more occurances of 3 than 1 in a supposedly "random" sequence. In such cases you would generally use a workaround like ( rand() % 100 ) / 10 or (float)rand() / (float)RAND_MAX * 10.0 (dunno if Squirrel has C-style casting).

tl;dr do it like this:

if( rand() % 100 < 10 ) doThing();
fluffrabbit

Posts: 570
Joined: 11 Apr 2019, 11:17

### Who is online

Users browsing this forum: No registered users and 1 guest