Skip to content

Instantly share code, notes, and snippets.

@jonofoz
Last active February 8, 2019 15:29
Show Gist options
  • Save jonofoz/ed19bd4f4640d783b1df97c0896bef09 to your computer and use it in GitHub Desktop.
Save jonofoz/ed19bd4f4640d783b1df97c0896bef09 to your computer and use it in GitHub Desktop.
A simple guessing game I wrote in C++.
/* While still playing,
The computer generates a number.
The user guesses the number.
While that number isn't correct,
Find out if the user's guess is correct this time.
If so,
They win, ask them if they want to play again
If they do,
Go back to line 2.
If they don't,
They're done, the game ends
If not,
Make them re-guess.
Go back to line 4.
*/
#include <iostream>
void guessingGame()
{
bool playing = true;
do
{
srand(time(NULL));
int magicNumber = rand() % 25 + 1;
int guessNumber = 0;
printf("Enter your guess (0 - 25): ");
std::cin >> guessNumber;
// To start, the user has not guessed the correctGuess.
bool correctGuess = false;
while (!correctGuess)
{
if (guessNumber == magicNumber)
{
printf("\n\nYou win! The number was %d.\n\n", magicNumber);
// Then this while loop will end since the player guessed the number.
correctGuess = true;
// validAnswer prevents the user from entering anything but 'y' or 'n'.
// That is, it will keep asking until the player enters a 'y' or 'n'.
bool validAnswer = false;
while (!validAnswer)
{
char playAgain = ' ';
printf("\nPlay again? (y) or (n): ");
std::cin>>playAgain;
if (playAgain == 'n')
{
printf("\n\nBye!");
validAnswer = true;
playing = false;
}
else if (playAgain == 'y')
{
printf("\nOkay!\n");
validAnswer = true;
}
else
{
char playAgain = ' ';
validAnswer = false;
}
}
}
else if (guessNumber < magicNumber)
{
correctGuess = false;
printf("Nope, the number is HIGHER.\nguess again: (0 - 25): ");
std::cin >> guessNumber;
}
else
{
correctGuess = false;
printf("Nope, the number is LOWER.\nguess again: (0 - 25): ");
std::cin >> guessNumber;
}
}
} while (playing);
}
int main()
{
guessingGame();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment