home *** CD-ROM | disk | FTP | other *** search
/ Beginning C++ Through Gam…rogramming (2nd Edition) / BCGP2E.ISO / source / chapter08 / critter_caretaker.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2004-04-11  |  2.0 KB  |  112 lines

  1. //Critter Caretaker
  2. //Simulates caring for a virtual pet
  3.  
  4. #include <iostream>
  5.  
  6. using namespace std;
  7.  
  8. class Critter
  9. {
  10. public:          
  11.     Critter(int hunger = 0, int boredom = 0); 
  12.     void Talk();
  13.     void Eat(int food = 4);
  14.     void Play(int fun = 4);
  15.  
  16. private:
  17.     int m_Hunger;
  18.     int m_Boredom;
  19.  
  20.     int GetMood() const;
  21.     void PassTime(int time = 1);
  22.  
  23. };
  24.  
  25. Critter::Critter(int hunger, int boredom):
  26.     m_Hunger(hunger),
  27.     m_Boredom(boredom)
  28. {}
  29.  
  30. inline int Critter::GetMood() const 
  31. {
  32.     return (m_Hunger + m_Boredom);
  33. }
  34.  
  35. void Critter::PassTime(int time)
  36. {
  37.     m_Hunger += time;
  38.     m_Boredom += time;
  39. }
  40.  
  41. void Critter::Talk()
  42. {
  43.     cout << "I'm a critter and I feel ";
  44.     int mood = GetMood();
  45.     if (mood > 15)
  46.         cout << "mad.\n";
  47.     else if (mood > 10)
  48.         cout << "frustrated.\n";
  49.     else if (mood > 5)
  50.         cout << "okay.\n";
  51.     else
  52.         cout << "happy.\n";
  53.     PassTime();
  54. }
  55.  
  56. void Critter::Eat(int food) 
  57. {
  58.     cout << "Brruppp.\n";
  59.     m_Hunger -= food;
  60.     if (m_Hunger < 0)
  61.         m_Hunger = 0;
  62.     PassTime();
  63. }
  64.  
  65. void Critter::Play(int fun)
  66. {
  67.     cout << "Wheee!\n";
  68.     m_Boredom -= fun;
  69.     if (m_Boredom < 0)
  70.         m_Boredom = 0;
  71.     PassTime();
  72. }
  73.  
  74. int main()
  75. {
  76.     Critter crit;
  77.  
  78.     int choice = 1;  //start the critter off talking
  79.     while (choice != 0)
  80.     {
  81.         cout << "\nCritter Caretaker\n\n";
  82.         cout << "0 - Quit\n";
  83.         cout << "1 - Listen to your critter\n";
  84.         cout << "2 - Feed your critter\n";
  85.         cout << "3 - Play with your critter\n\n";
  86.  
  87.         cout << "Choice: ";
  88.         cin >> choice;
  89.  
  90.         switch (choice)
  91.         {
  92.         case 0:    
  93.             cout << "Good-bye.\n";
  94.             break;
  95.         case 1:    
  96.             crit.Talk();
  97.             break;
  98.         case 2:    
  99.             crit.Eat();
  100.             break;
  101.         case 3:    
  102.             crit.Play();
  103.             break;
  104.         default:
  105.             cout << "\nSorry, but " << choice << " isn't a valid choice.\n";
  106.         }
  107.     }
  108.  
  109.     return 0;
  110. }
  111.  
  112.