home *** CD-ROM | disk | FTP | other *** search
/ C Programming Starter Kit 2.0 / SamsPublishing-CProgrammingStarterKit-v2.0-Win31.iso / tybc4 / game2.cpp < prev    next >
C/C++ Source or Header  |  1993-04-28  |  1KB  |  76 lines

  1. #include <stdlib.h>
  2. #include <iostream.h> 
  3. #include <time.h>
  4.  
  5. enum boolean { false, true }; 
  6.  
  7. // declare a global random number generating function
  8. int random(int maxVal)
  9. { return rand() % maxVal; }
  10.                                
  11. class game 
  12.   protected:
  13.     int n;
  14.     int m;
  15.     int MaxIter;
  16.     int iter;
  17.     boolean ok;
  18.     void prompt();
  19.     void examineInput();
  20.     
  21.   public:
  22.     game();
  23.     void play();
  24. };         
  25.  
  26. game::game()
  27. {
  28.   MaxIter = 11;
  29.   iter = 0;
  30.   ok = true;
  31.  
  32.   // reseed random-number generator
  33.   srand((unsigned)time(NULL));
  34.   n = random(1001);
  35.   m = -1;
  36. }                      
  37.     
  38. void game::prompt()
  39. {    
  40.   cout << "Enter a number between 0 and 1000 : ";
  41.   cin >> m;
  42.   ok = (m < 0) ? false : true;
  43. }            
  44.  
  45. void game::examineInput()
  46. {
  47.   // is the user's guess higher?
  48.   if (m > n)
  49.     cout << "Enter a lower guess\n\n";
  50.   else if (m < n)
  51.     cout << "Enter a higher guess\n\n";
  52.   else 
  53.     cout << "You guessed it! Congratulations.";
  54. }
  55.  
  56. void game::play()
  57. {
  58.   // loop to obtain the other guesses
  59.   while (m != n && iter < MaxIter && ok) {
  60.     prompt();
  61.     iter++;
  62.     examineInput();
  63.   }
  64.   // did the user guess the secret number
  65.   if (iter >= MaxIter || ok == 0)
  66.     cout << "The secret number is " << n << "\n";
  67. }
  68.  
  69. main()
  70. {          
  71.   game g;
  72.   
  73.   g.play();
  74.   return 0;
  75. }