// guess.cpp : Defines the entry point for the console application. // // Guess is a simple game where the player has 5 tries to guess a random number the computer chose. #include /* Include srand and rand */ #include /* Include printf() */ #include /* Include time() */ /* Define constant values */ #define NUMBER_OF_TRIES 5 // Guess the number 5 times until game over #define TRIESLEFT "You have %i tries left: " #define TOOLOW "Computer: The number you entered is too low\n" // This is a polite computer that apologizes when you guess incorrectly #define TOOHIGH "Computer: The number you entererd is too high\n" #define WINNER "CONGRATULATIONS, You won, the number %i is correct!\n" #define LOSER "SORRY YOU LOST, The number I thought of was %d\n" /* Define game variables */ int i, number, result, answer, tries = NUMBER_OF_TRIES; /* GuessNumber(int n) Compare the number n with the number computer "thought" of and return a comparative answer Return value: ( -1 ) if the number is too low, ( 1 ) if the number is too high or ( 0 ) if the numbers match */ int GuessNumber(int n) { int ret; n == number ? ret = 0 : (n > number) ? ret = 1 : ret = -1; return ret; } /* InitGame() Let the computer pick a random number */ void InitGame() { printf("InitGame()...\n"); srand(time(NULL)); // Reset number = rand()%100; // Generate the random number printf( "Computer: I have thought of a number between 0 and 100. Can you guess it?\n", number); } /* Play() This is where gameplay takes place */ void Play() { printf("Play(): "); printf("Please enter the number below.\n"); // Ask the player to guess the number, the number of times defined in 'tries' variable while ( tries ) { printf( TRIESLEFT, tries ); result = scanf( "%d", &i ); answer = GuessNumber(i); if (answer == 0) /* Correct answer */ { printf( WINNER, number ); return; } else answer < 0 ? printf( TOOLOW ) : printf( TOOHIGH ); tries--; } // Game over, // At this point the player has exceeded the number of tries, and still hasn't guessed the number printf( LOSER, number ); } /* Destroy() This is where we would destroy allocated memory, etc. Because Guess is a very simple game, we have nothing to do here, But this would be an important step in an advanced computer game */ void Destroy() { printf("DestroyGame()\n"); } /* int main() Program entry point */ int main(int argc, char* argv[]) { InitGame(); Play(); Destroy(); return 0; }