Mail Archives: djgpp/1998/02/05/03:31:43
On Wed, 4 Feb 1998 22:16:07 -0500 in comp.os.msdos.djgpp James W Sager
Iii <sager+@andrew.cmu.edu> wrote:
: If you want to make it so you can get TRUE random variables:
: void randomize(void)
: {
: remove_timer();
: srandom(time(0));
: install_timer();
: }
: yeah, its clunky that you have to uninstall the timer, but it
: works well none the less.
For anyone confused by those *_timer calls, they're Allegro functions
which do exactly what they say :). I think it's preferable, though,
to get your value from the system clock before initialising Allegro.
There are several problems with the above.
Firstly (general point), the `time' function's return value only
increments once every second, so if you call the above randomize
function with any frequency you'll get the same random sequence
several times over.
Secondly (Allegro-specific), removing Allegro's timer module
temporarily will probably cause several other Allegro components to
barf, notably the MIDI player and IIRC the mouse handler. If you're
using retrace simulation, that will go down too, and of course any
user timers installed will be removed also. In short, if you actually
needed Allegro's timers in the first place, removing them isn't a very
good plan. :)
My suggested solution is to grab a value from `time' on startup, and
store it in a static or global variable. On each call to randomize,
increment this variable when using its value; this ensures that you
use a different seed each time. Okay, they're fairly predictable, but
that shouldn't matter too much.
Untested code follows (sorry, the web cross compiler is disabled):
---- start ----
#include <time.h>
#include <stdlib.h>
static random_seed = 0;
void random_init() {
random_seed = time (NULL);
}
void randomise() {
srandom (random_seed++);
}
----- end -----
You'd call `random_init' on startup, before initialising Allegro, and
then you can call `randomise' as much as you like, whenever you like.
You can of course replace `srandom' with `srand', or even seed both if
you like.
--
george DOT foot AT merton DOT oxford DOT ac DOT uk
Remember what happened to the dinosaurs.
- Raw text -