Before you do a game, you need to get a random number.
1 rand ()% (end-start+1) +start;
The parameter end and start are set to get the range of random numbers, and to get close to the real random number you need to set a seed, the more common method is to use the current time as a seed, in the cocos2d-x to provide a way to get time, and get more accurate time
1 cc_timeval psv;2 cctime::gettimeofdaycocos2d (&PSV, NULL); 3 unsigned long int seed = psv.tv_sec*1000 + psv.tv_usec/1000;
The resulting time can be accurate to the millisecond level.
The requirement of a project is to get a set of random numbers, which is to use a loop to get a large number of random numbers, and at the beginning it does this:
1//carddispatcher.cpp 2 3 int ccarddispatcher::getrandomnumber () {4 cc_timeval PSV; 5 cctime:: Gettimeofdaycocos2d (&PSV, NULL); 6 unsigned long int seed = psv.tv_sec*1000 + psv.tv_usec/1000; 7 srand (seed); 8 9 int randnumber = random ( 0) return randnumber;11}12 int ccarddispatcher::random (int start, int end) { return ccrandom_ 0_1 () *end+start;16}18//maingamelayer.cpp20 bool Maingamelayer::init () { cclayer::init (); This->schedule (Schedule_selector (Maingamelayer::getcardnumber), 1.0), return true;25}26-void Maingamelayer::getcardnumber (float dt) { randomnumber = Ccarddispatcher::sharedispatcher () GetRandomNumber (); Cclog ("%d", randomnumber); 30}
When debugging, we find that the random number is very regular ...
It was a strange feeling that I had been searching the internet for a long time, and I didn't find any problems (maybe I didn't watch the tutorial carefully, haha). Then suddenly feel, should not put the seed set to the outside of the loop, and then the source code changes as follows:
1//carddispatcher.cpp 2 3 int ccarddispatcher::getrandomnumber () {4 int randnumber = random (0, ten); 5 return randnumber; 6} 7 8 int ccarddispatcher::random (int start, int end) {9 return ccrandom_0_1 () *end+start;11 12}13 14 15 MAINGAMELAYER.CPP16-bool Maingamelayer::init () { cclayer::init (); cc_timeval psv;21 cctime:: Gettimeofdaycocos2d (&PSV, NULL); unsigned long int seed = psv.tv_sec*1000 + psv.tv_usec/1000;23 srand ( Seed), This->schedule (Schedule_selector (Maingamelayer::getcardnumber), 1.0), return true;26}27 maingamelayer::getcardnumber void (float dt) { randomnumber = Ccarddispatcher::sharedispatcher () GetRandomNumber (); Cclog ("%d", randomnumber); 31}
Then debug, success.
So, set the seed position to put the loop outside .....
Cocos2d-x on the problem of obtaining random numbers