3

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?

tshepang
  • 12,111
  • 21
  • 91
  • 136
wirher
  • 916
  • 1
  • 8
  • 26

2 Answers2

10

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
}
Syntactic Fructose
  • 18,936
  • 23
  • 91
  • 177
  • 3
    Not "complete random", it's still pseudo-random, but starting from another point in the numbers list. – Luke B. Nov 09 '12 at 18:25
  • Really, I see when was my fault. I've got 2 "for" loops for each Y and X for every tile and I was calling srand([...]) each time. This was giving me map full of walls or full of free places. Doing srand before loops is giving really nice results. Thank you very much! – wirher Nov 09 '12 at 21:12
  • Caveat: this practice has led to replay attack vulnerabilities in some software. The random challenge was the same for every connection within the same one-second window, and so the attacker could snoop the correct answer from a legitimate user and provide the same response to authenticate their own connection, so long as they made their own connection within the same one-second window. – sh1 Jun 17 '13 at 11:16
3

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;    
}
Alex Wade
  • 659
  • 1
  • 7
  • 27