Tuesday, 14 September 2010

To random or not to random...

Well I have gotten closer to adding the level completions stuff to the game now, at the moment it calculates the totals of the stuff required for the player to complete the level. Next step would be to make this 'visible' to the player at the beginning of the level.

This may sound easy BUT C++ isnt the best thing to generate random numbers with you have the 'next to useless' rand function, but thanks to Martin Baeker I have now managed to cobble together some very useful functions;

int randInt(const int &mins, const int &maxs)


int range = maxs - mins;

int number = ( ((double)rand()/(double)RAND_MAX) *range);

return (number +mins);


float randFloat(const float& mins, const float& maxs)


float range = maxs - mins;

float num = ( ((double)rand()/(double)RAND_MAX) *range);

return (num + mins);


I can now use these to generate integers or floats for the game to function correctly. You can still use srand to change the seed but the functions will now work as required. I have shared them here to hopefully help another programmer out of the sticky situation that rand generates. Before you all jump up and go 'but you could call rand() %( max - min )' this DOES NOT WORK on XCode only in Visual C++ as far as I know, with XCode you will get a loverly EXC_ARITHMETIC error. The above code is 100% cross platform friendly.

Hope it helps someone somwhere but the credit for it should go to Martin Baeker as if it wasnt for his donkey work I wouldnt have been able to cobble the functions together :)

More soon...

No comments:

Post a Comment