www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/02/05/03:31:43

From: George Foot <mert0407 AT sable DOT ox DOT ac DOT uk>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Easy random things.
Date: 5 Feb 1998 08:11:18 GMT
Organization: Oxford University, England
Lines: 63
Message-ID: <6bbs76$3v0$4@news.ox.ac.uk>
References: <199802050139 DOT RAA05660 AT adit DOT ap DOT net> <YoqGvrC00XcY0BKGY0 AT andrew DOT cmu DOT edu>
NNTP-Posting-Host: sable.ox.ac.uk
Mime-Version: 1.0
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

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 -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019