Random.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. #ifdef JA2_PRECOMPILED_HEADERS
  2. #include "JA2 SGP ALL.H"
  3. #elif defined( WIZ8_PRECOMPILED_HEADERS )
  4. #include "WIZ8 SGP ALL.H"
  5. #else
  6. #include "Random.h"
  7. #endif
  8. #ifdef PRERANDOM_GENERATOR
  9. UINT32 guiPreRandomIndex = 0;
  10. UINT32 guiPreRandomNums[ MAX_PREGENERATED_NUMS ];
  11. #ifdef JA2BETAVERSION
  12. UINT32 guiRandoms = 0;
  13. UINT32 guiPreRandoms = 0;
  14. BOOLEAN gfCountRandoms = FALSE;
  15. #endif
  16. #endif
  17. void InitializeRandom()
  18. {
  19. // Seed the random-number generator with current time so that
  20. // the numbers will be different every time we run.
  21. srand( (unsigned) time(NULL) );
  22. #ifdef PRERANDOM_GENERATOR
  23. //Pregenerate all of the random numbers.
  24. for( guiPreRandomIndex = 0; guiPreRandomIndex < MAX_PREGENERATED_NUMS; guiPreRandomIndex++ )
  25. {
  26. guiPreRandomNums[ guiPreRandomIndex ] = rand();
  27. }
  28. guiPreRandomIndex = 0;
  29. #endif
  30. }
  31. // Returns a pseudo-random integer between 0 and uiRange
  32. UINT32 Random(UINT32 uiRange)
  33. {
  34. // Always return 0, if no range given (it's not an error)
  35. #ifdef JA2BETAVERSION
  36. if( gfCountRandoms )
  37. {
  38. guiRandoms++;
  39. }
  40. #endif
  41. if (uiRange == 0)
  42. return(0);
  43. return rand() * uiRange / RAND_MAX % uiRange;
  44. }
  45. BOOLEAN Chance( UINT32 uiChance )
  46. {
  47. return (BOOLEAN)(Random( 100 ) < uiChance);
  48. }
  49. #ifdef PRERANDOM_GENERATOR
  50. UINT32 PreRandom( UINT32 uiRange )
  51. {
  52. UINT32 uiNum;
  53. #ifdef JA2BETAVERSION
  54. if( gfCountRandoms )
  55. {
  56. guiPreRandoms++;
  57. }
  58. #endif
  59. if( !uiRange )
  60. return 0;
  61. //Extract the current pregenerated number
  62. uiNum = guiPreRandomNums[ guiPreRandomIndex ] * uiRange / RAND_MAX % uiRange;
  63. //Replace the current pregenerated number with a new one.
  64. //This was removed in the name of optimization. Uncomment if you hate recycling.
  65. //guiPreRandomNums[ guiPreRandomIndex ] = rand();
  66. //Go to the next index.
  67. guiPreRandomIndex++;
  68. if( guiPreRandomIndex >= (UINT32)MAX_PREGENERATED_NUMS )
  69. guiPreRandomIndex = 0;
  70. return uiNum;
  71. }
  72. BOOLEAN PreChance( UINT32 uiChance )
  73. {
  74. return (BOOLEAN)(PreRandom( 100 ) < uiChance);
  75. }
  76. #ifdef JA2BETAVERSION
  77. void CountRandomCalls( BOOLEAN fStart )
  78. {
  79. gfCountRandoms = fStart;
  80. if( fStart )
  81. {
  82. guiRandoms = 0;
  83. guiPreRandoms = 0;
  84. }
  85. }
  86. void GetRandomCalls( UINT32 *puiRandoms, UINT32 *puiPreRandoms )
  87. {
  88. *puiRandoms = guiRandoms;
  89. *puiPreRandoms = guiPreRandoms;
  90. }
  91. #endif
  92. #endif