Game Development Reference
In-Depth Information
dependent on another thread, which was impossible to synchronize. When we used one CRandom class
for each subsystem of the game, the problem disappeared.
Pseudo-Random Traversal of a Set
Have you ever wondered how the
button on your CD player works? It will
play every song on your CD randomly without playing the same song twice. That
random
sa
really useful solution for making sure players in your games see the widest variety of
features like objects, effects, or characters before they have the chance of seeing the
same ones over again.
The following code uses a mathematical feature of prime numbers and quadratic
equations. The algorithm requires a prime number larger than the ordinal value of
the set you want to traverse. If your set had 10 members, your prime number
would be 11. Of course, the algorithm doesn
'
t generate prime numbers; instead, it
just keeps a select set of prime numbers around in a lookup table. If you need bigger
primes, there
'
'
s a convenient website for you to check out.
Here
s how it works. A skip value is calculated by choosing three random values
greater than zero. These values become the coefficients of the quadratic, and the
domain value (x) is set to the ordinal value of the set:
'
Skip = RandomA * (members * members) + (RandomB * members) + RandomC
Armed with this skip value, you can use this piece of code to traverse the entire set
exactly once, in a pseudo-random order:
nextMember += skip;
nextMember %= prime;
The value of skip is so much larger than the number of members of your set that the
chosen value seems to skip around at random. Of course, this code is inside a while
loop to catch the case where the value chosen is larger than your set but still smaller
than the prime number. Here ' s the class definition:
class PrimeSearch
{
static int prime_array[];
int skip;
int currentPosition;
int maxElements;
int *currentPrime;
int searches;
 
 
Search WWH ::




Custom Search