Jump to content
chain

Guess My Number

Recommended Posts

  • Administrators

old game I wrote. This was probably the first or second game I wrote using random numbers and enumerated types. The computer picks a number, and you try to guess it. Very basic and simple, but it was a beginner project. Now, looking back, I could think of a million ways to rewrite this game, with 100 more features and far more memory efficient. This is just an example code, all in all. So, if you find bugs, don't post them, as I have no intention of fixing them. I'll post better games, and codes soon enough. More games will be posted at my forum.

 

#include <iostream>
#include <cstdlib>
#include <time.h>

using std::cout;
using std::cin;

int main()
{
  enum difficulty {EASY = 10, NORMAL = 100, HARD = 1000};
  difficulty diff = NORMAL;

  int uDiff, pGuess, pGuesses = 0;

  cout << "Welcome to Guess My Number!\n";
  cout << "Enter 0 at any time to quit\n";

  cout << "Enter the difficulty (1-3): ";
  cin >> uDiff;
  if (uDiff == 0) { cout << "Thanks for playing! Goodbye."; return 0; }
  switch (uDiff)
  {
    case 1:
      diff = EASY;
      break;
    case 2:
      diff = NORMAL;
      break;
    case 3:
      diff = HARD;
      break;
    default:
      do {
      cout << "Invalid difficulty!\n";
      cout << "Enter the difficulty (1-3): ";
      cin >> uDiff;
      }
      while (uDiff > 4);

  }
  srand(time(0));
  unsigned int cNum = (rand() % diff) + 1;
  cout << "Enter your guess: ";
  cin >> pGuess;
  while (pGuess != cNum)
  {
    if (pGuess == 0)
    {
      cout << "Thanks for playing! Goodbye.";
      return 0;
    }
    if (pGuess < cNum)
    {
      cout << "Too low! Try again.\n";
    }
    if (pGuess > cNum)
    {
      cout << "Too high! Try again.\n";
    }
    cout << "Enter your guess: ";
    cin >> pGuess;
  }
  pGuesses++;
  cout << "\nYou guessed correctly after " << pGuesses << " attempts.\n";
  cout << "The number was: " << cNum << "\n";
  cin.get();
  return 0;
}

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...


×
×
  • Create New...