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;
}
Cool, I got it to compile on OS X and here were my results:
Welcome to Guess My Number!
Enter 0 at any time to quit
Enter the difficulty (1-3): 3
Enter your guess: 5
Too low! Try again.
Enter your guess: 100
Too low! Try again.
Enter your guess: 1000
Too high! Try again.
Enter your guess: 500
Too high! Try again.
Enter your guess: 300
Too low! Try again.
Enter your guess: 400
Too high! Try again.
Enter your guess: 350
Too high! Try again.
Enter your guess: 325
Too low! Try again.
Enter your guess: 335
Too high! Try again.
Enter your guess: 330
Too low! Try again.
Enter your guess: 333
Too high! Try again.
Enter your guess: 332
You guessed correctly after 11 attempts.
The number was: 332