I had fun learning the basics of C++ in this section and can’t wait to start the next one!
My code is mostly the same as the instructor’s. However, I used my own story for the game.
#include <iostream>
#include <ctime>
void PrintIntroduction(int Difficulty)
{
// Print explanation messages to the terminal
std::cout << "\n\n";
std::cout << "=================================================================\n";
std::cout << "|A jinni tells you to solve a puzzle to get out of maze " << Difficulty << "... |\n";
std::cout << "|Enter the correct combination of numbers to solve the puzzle |\n";
std::cout << "=================================================================\n";
}
bool PlayGame(int Difficulty)
{
PrintIntroduction(Difficulty);
const int NumberA = rand() % Difficulty + Difficulty;
const int NumberB = rand() % Difficulty + Difficulty;
const int NumberC = rand() % Difficulty + Difficulty;
const int NumberSum = NumberA + NumberB + NumberC;
const int NumberProduct = NumberA * NumberB * NumberC;
// Print NumberSum and NumberProduct to the terminal
std::cout << "\n+There are three numbers";
std::cout << "\n+The numbers add up to: " << NumberSum;
std::cout << "\n+The numbers multiply to give: " << NumberProduct << std::endl;
// Store player's guess
int GuessA, GuessB, GuessC;
std::cin >> GuessA >> GuessB >> GuessC;
int GuessSum = GuessA + GuessB + GuessC;
int GuessProduct = GuessA * GuessB * GuessC;
// Check if player's guess is correct
if (GuessSum == NumberSum && GuessProduct == NumberProduct)
{
std::cout << "\nYou got out of this maze...";
return true;
}
else
{
std::cout << "\nThe jinni gives you another chance... Try again";
return false;
}
}
int main()
{
srand(time(NULL)); // seeding rand(), creating differenct sequences based on time of day
int LevelDifficulty = 1;
const int MaxDifficulty = 5;
while (LevelDifficulty <= MaxDifficulty) // Loops game until all levels completed
{
bool bLevelComplete = PlayGame(LevelDifficulty);
std::cin.clear(); // Clears any error flags
std::cin.ignore(); // Discards the input buffer; up to one character only
if (bLevelComplete)
{
++LevelDifficulty;
}
}
std::cout << "\n\nYou cleared all the mazes...\nCongratulations!";
return 0;
}