[Kde-games-devel] Reproducing random numbers

Ian Wadham ianw2 at optusnet.com.au
Mon Apr 13 05:12:40 CEST 2009


While working on the record/replay feature for KGoldrunner I have
struck a couple of problems with random numbers.  I would
appreciate any help or reassurance you can offer re the solutions
I have adopted.

Enemies in KGoldrunner depend on random numbers to decide
where to reappear after being killed and when to pick up or drop
gold.  Up till now the game has been using C library rand() (man
3 rand) with a seed based on the time() function (man 2 time), so
that the levels play differently from one time to another.

That's all very well, but how do you get a replayed level to run exactly
the same as when it was recorded?  Random number generators
appear to have no way to "read out" a seed.  The solution adopted
was to generate a random integer when "live" play of a level is about to
start, then re-inject that number as the seed and also save it in the
"recording".  When playing back the recording, read in and use the
same seed.  This seems a bit dodgy, but it works.

The next problem I found was that something was "swallowing" a
number from rand() occasionally and it did not seem to be code in
KGoldrunner (logged every use of rand()).  Maybe some KDE or
Qt library classes use rand()?  The effect of the swallowing was
to completely mess up the course of play.

So I switched to using a single KRandomSequence object and
the problem seems to be solved.  Reading the code for KRS, the state
appears to be completely self-contained and private, except that
the code can call KRandom (and rand()?) if you do not supply a seed.

So am I right in thinking that use of KRandomSequence is
completely reproducible if you supply a seed before starting a
sequence of numbers?

Cheers, Ian w.




More information about the kde-games-devel mailing list