Question

I'm trying to write a simple ASCII style game with randomly generated world for Android terminal using c4droid IDE. It has C++ support and basically I'm generating array[width][height] tiles using the rule rand()%2 - 1 creates walkable tile, 0 is wall. But there is problem. Each time I'm 'randomly' generating map it looks the same - because rand() isn't really random. I heard about using entropy created by HDD's or another parts. Problem is I'm using it on android so it is being weird for me to implement as C++ is not being as used as Java so I couldn't find solution on google. so short question: How can I generate "pretty much real" random numbers using c++ on android?

Was it helpful?

Solution

you need to seed your random number generator with srand(time(NULL)). This allows the computer to use the system time to come up with pseudo-random numbers.

a link to reference: http://www.cplusplus.com/reference/clibrary/cstdlib/srand/

EDIT: it might be smart to note that you only need to seed the rand() function only once, usually at the beginning of the program.

int main()
{
 srand(time(NULL)) //only needed to be called ONCE
 //code and rand functions afterward
}

OTHER TIPS

I think rand() should work for what you're doing. Are you seeding the random number generator?

srand(time(NULL));
// Should be a different set of numbers each time you run.   
for(unsigned i = 0; i < 10; ++i) {
    cout << rand() % 2 - 1;    
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top