One of the most interesting things I’ve learned since completing the second section of my Udemy course on C++ game creation, is that of random number generation. In Android, this process was a little more straight forward, with everything behind the scene just being handled for you. You simply created a “random number generator” class and asked it for a random number within a range.

In C++, at least the way my instructor is teaching us, it is a bit different. It appears that you first need to “seed” the random number generator with some numbers. Here is what I learned:

// Seed our random number with time from system.

srand((int)time(0) * 10);

// Use the random to get a number between 0 and 199.

beeSpeed = ((rand() % 200) + 200);

// Now set the bee’s starting position.

srand((int)time(0) * 10);

float height = ((rand() % 700) + 100);

It is a little snippet from the commit with all the code to move bees and clouds on the screen.

So, if I understand correctly, you have to first seed the random number. From the instructor, an easy to grab item to seed it with that changes often is the time. So, we are seeding the random number generator with the time multiplied by a number of our choosing.

If you just used an static number, then I believe the returned random number will always be the same. By using the time, which continues to change, then you will grantee that you don’t get the same input seed, making a similar random return highly improbable.

cloud

Right now, the background includes a few moving clouds and a bee. Not much to see, but you are welcome to check it out at my GitLab.

Linux – keep it simple.

Leave a Reply

Your email address will not be published.