Triple X - Taming rand()

Well done for completing Triple X! :partying_face:

How did you get on working with the modulus operator and generating your random number ranges?

I would LOVE to see the results of your final game!

How did you get on in this section? How hard you find the game to play? :grin:

4 Likes

I went a slightly different route on generating random numbers using the STL <random> library, the Mersenne Twister engine and std::uniform_int_distribution, which also requires the addition of the /std:c++17 switch to the compiler:
cl /EHsc /std:c++17 triplex.cpp
Code:

#include <iostream>
#include <random>

// Prints level detail and objective of the game
void PrintIntroduction(const int difficulty)
{
    std::cout << "You're a secret agent breaking into a level " << difficulty << " secure server room..." << std::endl;
    std::cout << "You need to enter the correct codes to continue..." << std::endl;
    std::cout << std::endl;
}

// For debug purposes, prints the codes that are used to create the clues
void PrintCodesDebug(const int codeA, const int codeB, const int codeC)
{
    std::cout << "\t****DEBUG****\tCodes are:\t" << codeA << " " << codeB << " " << codeC << std::endl;
}

// Prints the clue numbers and a prompt to input guesses
void PrintCluesAndPrompt(const int product, const int sum)
{
    std::cout << "\tThere are 3 numbers in the code" << std::endl;
    std::cout << "\tThe product of the numbers is " << product << std::endl;
    std::cout << "\tThe sum of the numbers is " << sum << std::endl;
    std::cout << std::endl;
    std::cout << "Enter your three guesses (separated by spaces, i.e. 1 2 3): ";
}

// For debug purposes, prints the values derived from input
void PrintGuessDebug(const int guessA, const int guessB, const int guessC, const int guessProduct, const int guessSum)
{
    std::cout << "****DEBUG****\tInput:\t\t" << guessA << " " << guessB << " " << guessC << std::endl;
    std::cout << "****DEBUG****\tInput Product:\t" << guessProduct << std::endl;
    std::cout << "****DEBUG****\tInput Sum:\t" << guessSum << std::endl;
}

// Clear error code and buffer
void ClearInput()
{
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

// Generate a random number between min and max inclusive
int GetRandomRange(int min, int max)
{
	static std::mt19937 engine{ std::random_device{}() };
	std::uniform_int_distribution dist{ min, max };

	return dist(engine);
}

// Main logic that returns success or failure for solving the puzzle
bool PlayGame(const int difficulty)
{
    PrintIntroduction(difficulty);

    // Declare three read-only values for the "secret code"
    const int CodeA = GetRandomRange(1, difficulty * 2);
    const int CodeB = GetRandomRange(1, difficulty * 2);
    const int CodeC = GetRandomRange(1, difficulty * 2);

    PrintCodesDebug(CodeA, CodeB, CodeC);

    // Calculate the sum and product for the "secret code" clues
    const int CodeProduct = CodeA * CodeB * CodeC;
    const int CodeSum = CodeA + CodeB + CodeC;

    PrintCluesAndPrompt(CodeProduct, CodeSum);

    // Declare variables and capture user input
    int GuessA, GuessB, GuessC;
    std::cin >> GuessA >> GuessB >> GuessC;

    // Perform result calculations
    const int GuessProduct = GuessA * GuessB * GuessC;
    const int GuessSum = GuessA + GuessB + GuessC;

    // PrintGuessDebug(GuessA, GuessB, GuessC, GuessProduct, GuessSum);

    // Test if guess calculations are the same as code calculations
    if (GuessProduct == CodeProduct && GuessSum == CodeSum)
    {
        std::cout << "You guessed correctly! Get ready for the next level..." << std::endl << std::endl;
        return true;
    }
    else
    {
        std::cout << "These are the wrong numbers! Try again!" << std::endl << std::endl;
        return false;
    }    
}

int main()
{
    //Game configuration settings
    const int MaxDifficulty = 6;
    int LevelDifficulty = 2;

    // Play the game until you've beat all the levels
    while (LevelDifficulty <= MaxDifficulty)
    {
        bool bLevelComplete = PlayGame(LevelDifficulty);

        ClearInput();

        // If you guess correctly, go up a level
        if (bLevelComplete)
        {
            LevelDifficulty++;
        }
    }

    // You've won, let the player know before exiting
    std::cout << "You hacked the server room! You win!" << std::endl;

    return 0;
}
13 Likes

Enjoyed the new exercise. I think it allowed for more customization than Bulls and Cows did in the original version of the course. I have a (very) little bit of C++ experience so I went ahead and did things slightly differently, taking more time to tinker with the flavor text and ASCII art. Looking forward to the next section!

/*
	A simple yet flavorful code-breaking game in which the user is tasked with
	guessing three integer values given their sum and product. With each of the
	twelve levels, the maximum potential size of the numbers increases, making
	for a greater arithmetic challenge. If the player solves all twelve puzzles,
	they win the game; if they fail, they are informed of their loss and shown a
	summary of their progress.
*/

#include <vector>
#include <iostream>
#include <ctime>

// Names for each riddle-protected gate
const std::vector<std::string> Gates{
	"the Nile", "Amon-Ra", "Mut", "Geb", "Osiris", "Isis",
	"Thoth", "Horus", "Anubis", "Seth", "Bastet", "Sekhmet"
};

// Ordinal numbers to describe gate position
const std::vector<std::string> Ordinals{
	"first", "second", "third", "fourth", "fifth", "sixth",
	"seventh", "eighth", "ninth", "tenth", "eleventh", "last"
};

// Introduce user to game
void PrintIntroduction()
{
	std::cout <<
		"            /\\ \n"
		"           /__\\ \n"
		"          /_| _\\ \n"
		"         /_|_ _|\\ \n"
		"        /__ _|_ _\\    `_,\n"
		"       /_|__  |_ |\\ - (_)-\n"
		"      /_|__|_ _ | _\\  ' `\n"
		"     / __| _|_ | _  \\ \n"
		"_ - / _ | __ | __ | _\\ _ - _ - _ - _ - _ TRIPLE X _ - _ - _ - _ -\n\n"
		"After months of arduous excavation, you have finally uncovered the\n"
		"entrance to the Lost Pyramid of Khaset. As you make your way through\n"
		"the winding crypt, a bright-eyed sphinx suddenly appears, blocking\n"
		"your path.\n\n";
}

// Pose riddle to user and indicate if answer is correct
bool PoseRiddle(const int CurrentGate)
{
	const int Difficulty = CurrentGate + 1;	// Offset index by 1
	const int CodeA = rand() % Difficulty + Difficulty;
	const int CodeB = rand() % Difficulty + Difficulty;
	const int CodeC = rand() % Difficulty + Difficulty;
	const int CodeSum = CodeA + CodeB + CodeC;
	const int CodeProduct = CodeA * CodeB * CodeC;
	std::cout <<	// Print riddle and prompt user for input
		"\"You have reached the Gate of " << Gates[CurrentGate] << ", " <<
		Ordinals[CurrentGate] << " barrier of twelve,\"\n"
		"says the sphinx. \"If you would venture deeper still, then rack\n"
		"your brains to solve this riddle:\n"
		"Added we are " << CodeSum << ".\n"
		"Multiplied we make " << CodeProduct << ".\n"
		"Speak to me these numbers three, and I will show the path you\n"
		"seek.\"\n";

	int GuessA = 0;
	int GuessB = 0;
	int GuessC = 0;
	std::cin.ignore(std::cin.rdbuf()->in_avail());
	std::cin >> GuessA >> GuessB >> GuessC;	// Get user input
	if (!std::cin)	// Handle non-integer input
		throw std::exception("The sphinx takes only integers!\n");

	if (GuessA + GuessB + GuessC == CodeSum &&	// Check if answer is correct
		GuessA * GuessB * GuessC == CodeProduct)
		return true;
	return false;
}

// Inform user of success or failure
void PrintOutcome(const bool bIsCorrect, const int CurrentGate)
{
	if (bIsCorrect) {
		std::cout <<	// Print success message
			"\nThe sphinx lowers its head with a smile. There is a puff of\n"
			"smoke, sudden darkness, then silence. When the pitch-black cloud\n"
			"clears away, you find the path ahead open. Taking your torch in\n"
			"hand, you forge ahead into the depths of the crypt.\n";

		if (CurrentGate < Gates.size())	// Print lead-in to next riddle
			std::cout << "Before long, another sphinx bars the way.\n\n";
		return;
	}
	std::cout <<	// Print failure message
		"\nA frown appears on the sphinx's face. Pity fills its eyes.\n"
		"\"Alas,\" it speaks, \"These numbers three are not the ones I need.\n"
		"I am afraid your journey is at an end. You made it to the Gate of\n" <<
		Gates[CurrentGate] << ", " << Ordinals[CurrentGate] << 
		" of two and ten.\"\n\n"
		"Sorry! You didn't beat the game.\n";
}

// Inform user they have beaten game
void PrintVictory()
{
	std::cout <<	// Print victory message
		"Seconds pass, then minutes. For the better part of an hour you grope\n"
		"along the dry stone walls, delving further and further into the\n"
		"ancient ruin. Finally, turning into a wide passage you see a light\n"
		"at the end of the corridor. Torches burn in bronze braziers, lining\n"
		"the walls of a small, square room. On a raised platform at its\n"
		"center lies the tomb of Anakhaten, first nomarch of Khaset.\n\n"
		"Congratulations! You beat the game.\n";
}

int main()
{
	PrintIntroduction();

	srand(time(NULL));	// Ensure randomness in riddle generation
	int CurrentGate = 0;	// Start at first gate
	while (CurrentGate < Gates.size()) {
		try {
			if (!PoseRiddle(CurrentGate)) {
				PrintOutcome(false, CurrentGate);
				return 0;	// Wrong answer ends the game
			}
			PrintOutcome(true, CurrentGate);
			++CurrentGate;	// Proceed to next gate
		}
		catch (std::exception & e) {
			std::cerr << e.what() << '\n';
			std::cin.clear();
		}
		catch (...) {
			std::cerr << "Unexpected error.\n";
			return 1;
		}
	}

	PrintVictory();
}
15 Likes
#include <iostream>
#include <ctime>

void PrintIntroduction(int Difficulty)
{
    //Print welcome message on the screen
    std::cout << "\n\nYou are a secret agent breaking into a level " << Difficulty;
    std::cout << " server room...\nEnter the correct code to continue...\n\n";
}

bool PlayGame(int Difficulty)
{
    PrintIntroduction(Difficulty);
    
    //Declaring 3 numbers in the code
    int CodeA = rand() % (Difficulty * Difficulty);
    int CodeB = rand() % (Difficulty * Difficulty);
    int CodeC = rand() % (Difficulty * Difficulty);

    int CodeSum = CodeA + CodeB + CodeC;
    int CodeProduct = CodeA * CodeB * CodeC;    

    //Print sum and product to the terminal
    std::cout << "There are 3 numbers in the code" ;
    std::cout << "\nThe codes add-up to: " << CodeSum;
    std::cout << "\nThe codes multipled to: " << CodeProduct << std::endl;
    
    int GuessA, GuessB, GuessC;
    std::cin >> GuessA >> GuessB >> GuessC;
    
    int GuessSum = GuessSum = GuessA + GuessB + GuessC;
    int GuessProduct = GuessA * GuessB * GuessC;

    //Check if the guess is correct
    if (CodeSum == GuessSum && GuessProduct == CodeProduct)
    {
        std::cout << "\nGood job agent you hacked some files!";
        return true;
    }
    else
    {
        std::cout << "\nDon\'t be reckless agent you might get caught!";
        return false;
    }
}


int main()
{
    srand(time(NULL)); // create new random sequence based on the time of day
    int LevelDifficulty = 1;
    const int MaxDifficulty = 5;
    while (LevelDifficulty <= MaxDifficulty){ //Loop 
        bool bLevelComplete = PlayGame(LevelDifficulty);
        std::cin.clear();
        std::cin.ignore();

        if (bLevelComplete) 
        {
            ++LevelDifficulty;
        }
        
    }
    std::cout << "\nCongratulations agent you hacked all the files!";
    return 0;
}
2 Likes

Finally motivated my self to learn c++ after many failed attempts. Had to redo this section twice before actually completing the game. Thank you for making me finally understand some of the things.

Here is my version of TripleX:

#include <iostream>
#include <ctime>
#include <Windows.h>
#include <time.h>
#include <stdio.h>

void Titel()
{
    // Titel
    std::cout << "  _____ ___ ___ ___ _    _____  __\n";
    std::cout << " |_   _| _ \\_ _| _ \\ |  | __\\ \\/ /\n";
    std::cout << "   | | |   /| ||  _/ |__| _| >  < \n";
    std::cout << "   |_| |_|_\\___|_| |____|___/_/\\_\\ \n";
    std::cout << "                       by munkhead\n\n";
}

void PrintIntroduction()
{
    // Print introduction to terminal
    std::cout << "\nYou are a secret agent hacking into a multilevel secure server." << std::endl;
    std::cout << "Crack the code to gain access...";


    // Print game mechanics to screen
    std::cout << "\n\n+ Type in the code seperated by spaces.\n";
    std::cout << "+ Confirm code by pressing enter.\n\n";
  
    // Initialize game
    std::cout << "Press enter to initalize";
    std::cin.get();
    Beep(200,200);
    Beep(250,200);
    Beep(300,200);

    // Break line
    std ::cout << "---------------------------\n\n";
}

bool PlayGame(int Difficulty)
{

    // Declare 3 number code
    const int CodeA = rand() % Difficulty + Difficulty;
    const int CodeB = rand() % Difficulty + Difficulty; 
    const int CodeC = rand() % Difficulty + Difficulty;

    const int CodeSum = CodeA + CodeB + CodeC;
    const int CodeProduct = CodeA * CodeB * CodeC;



    // Print code sum and product to terminal
    std::cout << "\nLEVEL " << Difficulty << std::endl;
    std::cout << "\nThere are 3 numbers in the code.\n\n";
    std::cout << "+ The code adds up to: " << CodeSum << std::endl;
    std::cout << "+ The code multiplys to give: " << CodeProduct << std::endl;

    

    // Store player guess
    int GuessA , GuessB, GuessC;
    std::cout << "\nEnter Code: ";
    std::cin >> GuessA;
    std::cin >> GuessB;
    std::cin >> GuessC;

    int GuessSum = GuessA + GuessB + GuessC;
    int GuessProduct = GuessA * GuessB * GuessC;

    // Check if player input is correct and print win or lose mesage to terminal
    if (GuessSum == CodeSum && GuessProduct == CodeProduct)
    {
        std::cout << "\n***ACCESS GRANTED***\n";
        Beep(200,200);
        Beep(400,200);
        return true;
        
    }
    else
    {
        std::cout << "\n!!!ACCESS DENIED!!!\n";
        Beep(150,200);
        Beep(150,200);
        return false;
    }

    std::cout << std::endl;
}

int main()
{
    
    srand(time(NULL));
    Titel();
    PrintIntroduction();

    int LevelDifficulty = 1;
    const int MaxLevel = 5;


    while (LevelDifficulty <= MaxLevel)
    {
        bool bLevelComplete = PlayGame(LevelDifficulty);
        std::cin.clear();
        std::cin.ignore();

        if (bLevelComplete)
        {
            std::cout << "\nPress enter to continue...\n" ;
            std::cin.get();
            ++LevelDifficulty;
        }
        else
        {
            std::cout << "\nPress enter to try again...\n";
            std::cin.get();
        }
        
    }

    std::cout << "\n\nCongratulations agent you made it, we have access to the files.\n\n\n\n";
    std::cout << "Thank you for playing\n";
    Titel();
    std::cin.get();
       
    return 0;
}
6 Likes

Wow my mind is blown after reading your code. You really created something unique and extraordinary!

Awesome Job!

1 Like

I had great fun with this one. Better than Bulls and Cows. I was able to complete the game, but had to use a calculator to figure out the last two codes. I didn’t do anything fancy with the code except to separate the intro from the rest of the game.

/* TrippleX
A Hackers Nightmare
Created 2019 */

#include
#include

void PrintLogo()
{
std::cout << " ____ ____ ____ ____ ____ __ ____ _ " << std::endl;
std::cout << " (
)( _ \( )( _ \( _ \( ) ( ___)( \/ )" << std::endl;
std::cout << " )( ) / )( )
/ )/ )( )) ) ( " << std::endl;
std::cout << " (
) ()\)(____)() (_) ()()(/\)" << std::endl;
std::cout << “\nYou are a secret agent breaking into a \n”;
std::cout << “server with multiple firewalls.”;
}

void PrintIntroduction(int Difficulty)
{
std::cout << "The current firewall is level " << Difficulty;
std::cout << “\nEnter the correct code to break past this firewall…\n”;
}

bool PlayGame(int Difficulty)
{
PrintIntroduction(Difficulty);
srand(time(NUL)); // Creates a new random sequence based on the time of day
const int CodeA = rand() % Difficulty + Difficulty;
const int CodeB = rand() % Difficulty + Difficulty;
const int CodeC = rand() % Difficulty + Difficulty;

const int CodeSum = CodeA + CodeB + CodeC;
const int CodeProduct = CodeA * CodeB * CodeC;

// Print sum/product to terminal
std::cout << "\n* There are 3 numbers in the code.";
std::cout << "\n* The codes add up to: " << CodeSum;
std::cout << "\n* The codes multiply to give: " << CodeProduct << "\n";

int GuessA, GuessB, GuessC;

// Store player guess
std::cout << "Please enter your 3 number guess separated by spaces\n";
std::cin >> GuessA >> GuessB >> GuessC;
std::cout << "You entered: \n" << GuessA << GuessB << GuessC << std::endl;
int GuessSum = GuessA + GuessB + GuessC;
int GuessProduct = GuessA * GuessB * GuessC;

// Compare guess to code. Print results to terminal
if (GuessSum == CodeSum && GuessProduct == CodeProduct) 
{
    std::cout << "\nYou got that code! Let's move on.\n";
    return true;
}
else
{
    std::cout << "\nYou did not choose the right code!\n";
    std::cout << "Be more careful and try again!\n";
    return false;
}

}

int main()
{
int LevelDifficulty = 1;
const int MaxLevel = 5;
PrintLogo();

while (LevelDifficulty <= MaxLevel) // Loop game until all levels completed
{
    bool bLevelComplete = PlayGame(LevelDifficulty);
    std::cin.clear(); // clears any erros
    std::cin.ignore();  // discards the buffer

    if (bLevelComplete) 
    {
        ++LevelDifficulty;
    }        
}
std::cout << "\nCongratuations! You broke through all of the firewalls.\n";
std::cout << "Get the files and get out of there!";
return 0;

}

1 Like

Great work!

Thx allot.

#include <iostream>
#include <ctime>

bool PlayGame(int Difficulty);
void PrintIntroduction(int Difficulty);

int main()
{
    srand(time(NULL));

    std::cout << std::endl;
    std::cout << "   @@@@@@@@@@@@  @@@@@@@@@@@@    @@@@@@@@@@@   @@@@@@@@@@    @@@           @@@@@@@@@@@@    @@@               @@@      @@@ \n";                                                       
    std::cout << "       @@@       @@@      @@@        @@@       @@@      @@@  @@@           @@@                @@@         @@@         @@@ \n";                                       
    std::cout << "       @@@       @@@      @@@        @@@       @@@      @@@  @@@           @@@                   @@@   @@@            @@@ \n";                                       
    std::cout << "       @@@       @@@@@@@@@           @@@       @@@@@@@@@@    @@@           @@@@@@@@@@@@             @@@               @@@ \n";                                                
    std::cout << "       @@@       @@@    @@@          @@@       @@@           @@@           @@@                   @@@   @@@            @@@ \n";                                
    std::cout << "       @@@       @@@     @@@         @@@       @@@           @@@@@@@@@@@@  @@@                @@@         @@@             \n";                                        
    std::cout << "       @@@       @@@      @@@    @@@@@@@@@@@   @@@           @@@@@@@@@@@@  @@@@@@@@@@@@    @@@               @@@      @@@ \n"; 

    int LevelDifficulty = 1;
    const int MaxDifficulty = 5; 

      while (LevelDifficulty <= MaxDifficulty) //Loop Until All Levels Completed
    {
        bool bLevelComplete = PlayGame(LevelDifficulty);
        std::cin.clear();
        std::cin.ignore();

        if (bLevelComplete)
        {
            ++LevelDifficulty; 
        }
        
    }
    std::cout << "You've obtained the information! now to get back to base so we can look over those specs.\n\n";
    return 0; 
}

void PrintIntroduction(int Difficulty)
{                                                  
    //Printing introduction To Terminal
    std::cout << std::endl;
    std::cout << "Greetings, you are a Biotech spy trying to break into the Tangent Technologies mainframe!\n";
    std::cout << "You are at the level " << Difficulty;
    std::cout << " firewall, you need to work out the correct code to break through!\n\n";
}

bool PlayGame(int Difficulty)
{      
    PrintIntroduction(Difficulty);    
    
    //Declaring 3 Digit Code 
    const int CodeA = rand() % Difficulty +Difficulty; 
    const int CodeB = rand() % Difficulty +Difficulty;  
    const int CodeC = rand() % Difficulty +Difficulty;

    const int CodeSum = CodeA + CodeB + CodeC;
    const int CodeProduct = CodeA * CodeB * CodeC;

    //Print CodeSum And CodeProduct To Terminal
    std::cout << "- There are 3 digits in the code\n";
    std::cout << "- The codes add-up to: " << CodeSum << std::endl; 
    std::cout << "- And multiplies to give: " << CodeProduct << std::endl << std::endl;

    //Store Player Guess
    int GuessA, GuessB, GuessC;
    std::cin >> GuessA >> GuessB >> GuessC;
    std::cout << std::endl;

    int GuessSum = GuessA + GuessB + GuessC;
    int GuessProduct = GuessA * GuessB * GuessC;

    //Checking Player Guess
    if (GuessSum == CodeSum && GuessProduct == CodeProduct) 
    {
        std::cout << "Success you've cracked this layer!\n\n";  
        return true;
    }   
    else
    {
        std::cout << "Rats that's not the right code... what else might it be?\n\n";  //Add Set Number Of Tries
        return false; 
    }
    
    
}

My current first attempt at this, thought I’d post this for now as it’s the basic end point but as we need to wait for the next section update I’m going to try and work on a few things to improve it and repost, like a limited number of attempts, and having it so range of number is large as I’m not a fan of losing all the lowest numbers as options when the difficulty increases as without mentioning it the player would likely not guess that by level 5 they should only be using a minimum value of 5.

It could be a cool idea to have the lecture end with a few suggestions of what people could do to further modify the game and suggest they think of others as a major thing I’m learning from this is that it’s not just the coding side of it that you need to learn, it’s the actual knowing what you want and finding how to do it, so fixing up bits of a finished game would be a great place to get people to start on this and share ideas with others on what they thought up.

1 Like

#include
#include

void PrintIntroduction(int Difficulty)
{
std::cout << " _ _ \n" << " ( )_ \n" << " ( )) \n";
std::cout << " (_ (_ . _) _) \n";
std::cout << “–>Enemies have our secreat file.\n”;
std::cout << “–>You have the task to infilrate in to the enemy’s servers.\n”;
std::cout << “–>You are a secret agent breaking into a level " << Difficulty << " secure server room.\n\n\n”;
std::cout << “+ You have to access the system without others knowing your presence.\n”;
std::cout << “+ You need to enter the correct codes to continue…\n”;//What to do to pass the level
std::cout << “+ If the code entered is wrong, it will alert the enemy\n\n”;
}

bool PlayGame(int Difficulty)
{
PrintIntroduction(Difficulty);

// Declare the 3 numbers of code.
const int CodeA = rand() % Difficulty + Difficulty;
const int CodeB = rand() % Difficulty + Difficulty;
const int CodeC = rand() % Difficulty + Difficulty;
// %(value) => so as to get a range between 0-9.
// +1 to offset.

const int CodeSum = CodeA + CodeB + CodeC;
const int CodeProduct = CodeA * CodeB * CodeC;

// Print hints to the terminal.
std::cout << "- According to sources the following information is known:\n";
std::cout << "- There are three numbers in the code.\n";
std::cout << "- The code add-up to: " << CodeSum ;
std::cout << "\n- The product of code's digits is: "<< CodeProduct ;

// Store plyer Guess.
int GuessA , GuessB , GuessC;
std::cout << "\n\n+ Enter the code: ";
std::cin >> GuessA >> GuessB >> GuessC;

int GuessSum = GuessA + GuessB + GuessC;
int GuessProduct = GuessA * GuessB * GuessC;

// Checks if the players guess is correct.
if ( GuessSum == CodeSum && GuessProduct == CodeProduct )
{    
    std::cout << "\nWell done!! You cleared the level.\n" << std::endl;
    return true;
}

else
{
    std::cout << "\n The enemies are alerted!! Try again.\n" << std::endl;
    return false;
}

}

int main() // The control function.
{
srand(time(NULL)); // Create new random sequence based on time of day.

int LevelDifficulty = 1;
const int MaxDifficulty = 10;

while ( LevelDifficulty <= MaxDifficulty ) // Loop until max level.
{
    bool bLevelComplete =  PlayGame(LevelDifficulty);
    std::cin.clear(); // Clear any error.
    std::cin.ignore(); // Discard the buffer.

    if (bLevelComplete)
    {
        ++LevelDifficulty;
    }
}

std::cout << "\n\n You cleared all the levels and injected the virus in the enemy servers\n\n MISSION ACCOMPLISHED\n\n";


return 0;

}

the first game. Its nice and after level 6 its really tough

#include
#include

void PrintIntroduction (int Difficulty)
{
// ASCI art here
std ::cout << R"(
, ,
,-{-/
,-~ , \ {-~~-,
,~ , ,,-~~-,,
,, { { } } }/ ; ,--/\ \ / / }/ /,/
; ,-./ \ \ { { ( /,; ,/ ,/
; / } }, --.___ / , ,/,/
| ,, ~.___,---} / ,,/ ,,; { { __ / ,/ ,,;
/ \ \ _,,{ ,{,;
{ } } /~\ .-:::-. (–, ;\ ,},; \\._./ / / , \ ,:::::::::, ~; \},/,; ,-=--…-/. ._ ;:::::::::::; ,{ /,; { / , ~ . ^~\:::::::::::<<~>-,,, -, ``,_ } /~~ . . ~ , .~~\:::::::; _-~ ;__,,-/\ /~, . ~ , ’ , . ::::;<<<~``` ``-,,__ ; / .\ / . ^ , ~ , . . ~\~ \\,,
/ , ,. ~ , ^ , ~ . . ~~~`, `-`--, \ / , ~ . ~ \ , ` . ^ ` , . ^ . , ` .`-,___,---,__
/ . ~ . \ ~ , . , , . ~ ^ , . ~ , .~---,___ / . , . ~ , \ ~ , . ^ , ~ . , ~ . ^ , ~ .-,

                                           -Daniel Hunt-)" << '\n';

std::cout << std::endl;

//story of the game below
std::cout << “The code to the secret genetic enhancer mechanism was hidden in the safe…\n”;
std::cout << “It was the most secure safe of that era, it required an unprecedented effort to crack this code…\n”;
std::cout << “a team of 15 people attempted to open the safe, unfortunately the security mechanism killed the majority of them…\n”;
std::cout << “it was left to one individual to make one last attempt to open the safe…\n”;
std::cout << "You need to enter the correct level “<< Difficulty;
std::cout << " codes to continue…\n”;
//story ends here
}

bool PlayGame (int Difficulty)
{

PrintIntroduction (Difficulty);

//declare 3 number code
const int CodeA = rand() % Difficulty + Difficulty;
const int CodeB = rand() % Difficulty + Difficulty;
const int CodeC = rand() % Difficulty + Difficulty;

/*
This is 
a multi-line 
coment
*/

const int CodeSum = CodeA + CodeB + CodeC;
const int CodeProduct = CodeA * CodeB * CodeC;

//  Print sum and product to the terminal
std::cout << std::endl;
std::cout << "There are 3 numbers in the code\n";
std::cout << "\nThe codes add up to: " << CodeSum;
std::cout << "\nThe codes multiply to give: " << CodeProduct;
std::cout << std::endl;

// Store player Guess
int GuessA, GuessB, GuessC;
std::cin >> GuessA >> GuessB >> GuessC;

// Check if players guess in correct
int GuessSum = GuessA + GuessB + GuessC;
int GuessProduct = GuessA * GuessB * GuessC;

if (GuessSum == CodeSum && GuessProduct == CodeProduct)
{
    std::cout << "You have entered the correct code, try at the next level";
    return true;
}

else
{
    std::cout << "\nThis is the wrong code, the facility will now self destruct...\n";
    std::cout << "But I will resurrect you to try again";
    return false;
}

}

int main()
{
srand(time(NULL)); // create new random sequence based on time of day

int LevelDifficulty = 1;
int const MaxLevel = 5;

while (LevelDifficulty <= MaxLevel) // Loop game until all levels completed
{
   
    bool bLevelComplete = PlayGame(LevelDifficulty);
    std::cin.clear(); //Clears any errors
    std::cin.ignore(); // Discards the buffer

    if (bLevelComplete) 
    {
        ++LevelDifficulty;
    }
    
}

std::cout << "\nCongratulations you have opened the safe!";

return 0;

}[quote=“Gavin_Milroy, post:1, topic:104962, full:true”]
Well done for completing Triple X! :partying_face:

How did you get on working with the modulus operator and generating your random number ranges?

I would LOVE to see the results of your final game!

How did you get on in this section? How hard you find the game to play? :grin:
[/quote]

progress so far!

I had great deals of fun working through this, here is what I had at the end of the guided lectures, but I think I am going to keep at it and expand what it can do some more.

#include <iostream>
#include <thread>
#include <chrono>
#include <ctime>

//This function pauses execution of code on this line for some acmount of time.
void Sleep(int milliseconds){
    std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
}

//This function takes some string and prints it to the terminal with a newline character at the end.
void PrintLine(std::string text)
{
    std::cout << text << std::endl;
    Sleep(30);
}

const std::string LaptopArt = "         +---------------+ \n"
                        "         |.-------------.| \n"
                        "         || Enter Code  || \n"
                        "         ||             || \n"
                        "         ||             || \n"
                        "         ||             || \n"
                        "         |+-------------+| \n"
                        "         +-..---------..-+ \n"
                        "         .---------------. \n "
                        "       / /=============\\ \\ \n"
                        "       / /===============\\ \\ \n"
                        "      /_____________________\\ \n"
                        "      \\_____________________/"; 

const std::string OutsideArt = "                                               /\\      /\\    \n"
                         "                                               ||______||    \n"
                         "                                               || ^  ^ ||    \n"
                         "                                               \\| |  | |/    \n"
                         "                                                |______|     \n"
                         "              __                                |  __  |     \n"
                         "             /  \\       ________________________|_/  \\_|__   \n"
                         "            / ^^ \\     /=========================/ ^^ \\===|  \n"
                         "           /  []  \\   /=========================/  []  \\==|  \n"
                         "          /________\\ /=========================/________\\=|  \n"
                         "       *  |        |/==========================|        |=|  \n" 
                         "      *** | ^^  ^^ |---------------------------| ^^  ^^ |--  \n"
                         "     *****| []  [] |           _____           | []  [] | |  \n"
                         "    *******        |          /_____\\          |      * | |  \n"
                         "   *********^^  ^^ |  ^^  ^^  |  |  |  ^^  ^^  |     ***| |  \n"
                         "  ***********]  [] |  []  []  |  |  |  []  []  | ===***** |  \n"
                         " *************     |         @|__|__|@         |/ |*******|  \n"
                         "***************   ***********--=====--**********| *********  \n"
                         "***************___*********** |=====| **********|*********** \n"
                         " *************     ********* /=======\\ ******** | *********  \n";

//This function prints our story introduction to the terminal
void PrintLevelIntro(int Difficulty)
{
    if (Difficulty == 1)
    {
    PrintLine("The van finally comes to a stop you look outside your window to see the dragon's mansion.");
    PrintLine(OutsideArt);
    Sleep(2000);
    PrintLine("Your team sneak quietly to the building, everything is going as planned.");
    PrintLine("They get to the front door and pop open the code panel, they splice in the antenna.");
    PrintLine("The link lights up on your terminal draswing your attention");
    PrintLine(LaptopArt);
    PrintLine("Your hacking software thinks for a moment then prints out:");
    } else if (Difficulty == 2){
        PrintLine("Level 2 Intro goes here");
    } else if (Difficulty == 3){
        PrintLine("Level 3 intro goes here");
    }
}
// This function prints out to console the success text for the current level
void PrintLevelSuccess(int Difficulty)
{
    if(Difficulty == 1){
        PrintLine("    Access Granted\n");
        PrintLine("Looking up at the cam feed you see the panel turn green and the door slides open for your team they filter into the building quietly.");
        }else if (Difficulty == 2)
        {
            PrintLine("Level 2 win!");
        }else if (Difficulty == 3)
        {
            PrintLine("Level 3 win!");
        }
}

//This function prints out to console the fail text for the current level
void PrintLevelFail(int Difficulty)
{
    if (Difficulty == 1)
    {
        PrintLine("    Access Denied notifying security");
        PrintLine("");
        PrintLine("Oh crap! Looking up at the cam feed you see the panel turn red and an alarm starts to blare, your team turn and run.");
    }else if (Difficulty == 2)
    {
            PrintLine("Level 2 failed :");
    }else if (Difficulty == 3)
    {
            PrintLine("Level 3 failed :");
    }
}

void PrintHint(int Difficulty, int CodeSum, int CodeProduct)
{
    PrintLine("    This is a level " + std::to_string(Difficulty) +  ", 3 number encryption");
    PrintLine("    The codes add-up to give: " + std::to_string(CodeSum));
    PrintLine("    The codes multiply to give: " + std::to_string(CodeProduct));
}

bool PlayGame(int Difficulty)
{
    PrintLevelIntro(Difficulty);
    //Generate our Code for the level
    int CodeOne, CodeTwo, CodeThree;
    if (Difficulty == 1 )
    {
        CodeOne = rand() % 3;
        CodeTwo = rand() % 3;
        CodeThree = rand() % 3;
    } else if (Difficulty == 2)
    {
        CodeOne = rand() % 5;
        CodeTwo = rand() % 5;
        CodeThree = rand() % 5;
    }else if (Difficulty == 3)
    {
        CodeOne = rand() % 7;
        CodeTwo = rand() % 7;
        CodeThree = rand() % 7;
    }else
    {
        CodeOne = rand() % 9;
        CodeTwo = rand() % 9;
        CodeThree = rand() % 9;
    }

    const int CodeSum = CodeOne + CodeTwo + CodeThree;
    const int CodeProduct = CodeOne * CodeTwo * CodeThree;

    //Store the players guess
    int GuessOne, GuessTwo, GuessThree, Try, GuessSum, GuessProduct;
    Try = 1;

    //Print our hint to the console
    PrintHint(Difficulty,CodeSum,CodeProduct);

    while (Try <= 3)
    {
        if(Try != 1){
            PrintLine("The line flashes incorrect " + std::to_string((4 - Try)) + " Tries remaining");
            PrintHint(Difficulty,CodeSum,CodeProduct);
        }
        //Get the players Guess
        std::cin >> GuessOne >> GuessTwo >> GuessThree;

        GuessSum = GuessOne + GuessTwo + GuessThree;
        GuessProduct = GuessOne * GuessTwo * GuessThree;

        //Check if the players guess is correct
        if (GuessSum == CodeSum && GuessProduct == CodeProduct)
        {
            PrintLevelSuccess(Difficulty);
            return true;
        }else
        {
        ++Try;
        }
    }
    PrintLevelFail(Difficulty);
    return false;
}

//This function is the entry point for the application and where the magic begins. 
int main()
{
    srand(time(NULL)); // Seed the randomness
    int Difficulty = 1;
    const int MaxDifficulty = 3;

    while (Difficulty <= MaxDifficulty) //Loop the game until all levels have been completed
    {
        bool bLevelComplete = PlayGame(Difficulty);
        std::cin.clear();
        std::cin.ignore();

        if (bLevelComplete)
        {
            ++Difficulty;
        }
    }

    PrintLine("\nThose chummers are no match for a master decker like yourself.");
    return 0;
}

I had a bit of C and C++ experience before this section. I had gone ahead and did a few things different, such as encapsulating everything individually for functionality.
I had previously used std::endl to end all my cout lines, but after researching the difference between \n and endl, I found out that \n is a faster solution to a new line and endl force flushes the buffer and to use it before cin. So I have altered my code to reflect that.

I plan on continuing with this game to take in the user’s name, to save the results to a text file for each user, and to see if I can implement a countdown timer, as my game is based on defusing bombs.

//Title:					tripleXGame.cpp
//Course:					Udemy Unreal Engine C++ Developer
//Author:					Ryn Ellis
//Date:						2019-05-17
//Description:				Code guessing game


//Libraries
#include <iostream>
#include <ctime>
#include <stdlib.h>

using namespace std;

//Function Definitions
void Opening();																		//Title and story message function
int AdditionCalculations(int first, int second, int third);							//Addition Calculations for code riddle function
int MultiplicationCalculations(int first, int second, int third);					//Multiplication Calculations for code riddle function
int PlayerAdditionCalculations(int first, int second, int third);					//Addition Calculations for code riddle function for the player
int PlayerMultiplicationCalculations(int first, int second, int third);				//Multiplication Calculations for code riddle function for the player
int PlayerInput();																	//Player code input function
void Boom();																		//Game ending if wrong code guessed
void Win();																			//Game ending if all the codes are guessed correctly
int Comparison(int codeSum, int playerSum, int codeProduct, int playerProduct);		//Comparison function to compare sums and products
bool PlayGame();																	//Actual game play function
bool ReplayGame();																	//To ask player if they would like to play again
void LevelIncrease();																//To increase the level of difficulty if player gets the correct code
int RandomNumberGenerator();


//Variables and Arrays
//Level Variables
int Difficulty = 1;			
const int MaxDifficulty = 10;	
bool bPlay = true;
//Code Number Array
int CodeNumber[3] = { 0, 0, 0 };
int Interval = 0;
//Mathematical Variables
int SumCodeTotal = 0;
int ProductCodeTotal = 0;
int PlayerSum = 0;
int PlayerProduct = 0;
//Player Information
int PlayersGuess[3] = { 0, 0, 0 };


//Main Program
int main()
{
	while (bPlay == true)
	{
		PlayGame();
		std::cin.clear();	//Clears any errors
		std::cin.ignore();  //Discards the buffer
	}
	return 0;
}


//Functions
void Opening()
{

	PlayerProduct = 0;
	PlayerSum = 0;
	SumCodeTotal = 0;
	ProductCodeTotal = 0;

	//This function prints the title of the game and the story behind the game.
	system("CLS");
	std::cout << "		     _________ _______ _________ _______  _        _______            \n";
	std::cout << "		     \\__   __/(  ____ )\\__   __/(  ____ )( \\      (  ____ \\  |\\     /| \n";
	std::cout << "			) (   | (    )|   ) (   | (    )|| (      | (    \\/  ( \\   / ) \n";
	std::cout << "			| |   | (____)|   | |   | (____)|| |      | (__       \\ (_) / \n";
	std::cout << "			| |   |     __)   | |   |  _____)| |      |  __)       ) _ (  \n";
	std::cout << "			| |   | (\\ (      | |   | (      | |      | (         / ( ) \\ \n";
	std::cout << "			| |   | ) \\ \\_____) (___| )      | (____/\\| (____/\\  ( /   \\ ) \n";
	std::cout << "			)_(   |/   \\__/\\_______/|/       (_______/(_______/  |/     \\|\n\n\n\n";
	


	std::cout << "	************************************************************************************************* \n";
	if (Difficulty == 1)
	{
		std::cout << "	*  You are a rookie bomb defuser.  There is a crisis in the building with " << MaxDifficulty << " bombs to defuse.	*\n";
		std::cout << "	*  You need to enter the correct codes on the devices in order to defuse them!			*\n";
		std::cout << "	*  Hurry before time runs out!									*\n";

	}
	else
	{
		std::cout << "	*  That's it rookie! You have defused the bomb!							*\n";
		std::cout << "	*  You only have " << MaxDifficulty - Difficulty + 1 << " left to defuse!								*\n";
	}
	
	std::cout << "	*												* \n";
	std::cout << "	*												* \n";
	std::cout << "	*  This is bomb " << Difficulty << ".										* \n";
	std::cout << "	*  There are three numbers in the code in order to defuse the bomb.				* \n";
	std::cout << "	*												* \n";
	std::cout << "	*												* \n";

	while (Interval < 3)
	{
		CodeNumber[Interval] = RandomNumberGenerator();
		++Interval;

	}
	Interval = 0;
	SumCodeTotal = AdditionCalculations(CodeNumber[0], CodeNumber[1], CodeNumber[2]);
	ProductCodeTotal = MultiplicationCalculations(CodeNumber[0], CodeNumber[1], CodeNumber[2]);

	std::cout << "	*  The sum of the three numbers equal " << SumCodeTotal << ".							*\n";
	std::cout << "	*  The product of the three numbers equal " << ProductCodeTotal << ".							*\n";
	std::cout << "	*												*\n";
	std::cout << "	*  You only have one chance to get this right and save everyone!				*\n";
	std::cout << "	*************************************************************************************************" << std::endl;
	std::cout << std::endl;

}

int AdditionCalculations(int First, int Second, int Third)
{
	//This function calculates the sum and the product of the three numbers for the code sequence
	SumCodeTotal = First + Second + Third;
	
	return SumCodeTotal;
}

int PlayerInput()
{
	//This function collects the player's guess	
	int I = 0;				//Used for incrementing through the array
	int Input = 0;

	std::cout << "			What is the code to defuse the bomb?  ";
	while (I< 3)
	{
		std::cin >> PlayersGuess[I];
		I++;
	}

	PlayerSum = PlayerAdditionCalculations(PlayersGuess[0], PlayersGuess[1], PlayersGuess[2]);

	PlayerProduct = PlayerMultiplicationCalculations(PlayersGuess[0], PlayersGuess[1], PlayersGuess[2]);

	return 0;
}

void Boom()
{
	//This function is for when the player guesses the wrong code
	system("CLS");
	std::cout << std::endl;
	std::cout << std::endl;
	std::cout << std::endl;
	std::cout << "		========    ====     ====   ====   ==== \n";
	std::cout << "		||     \\\\  //  \\\\   //  \\\\  ||  \\ /  || \n";
	std::cout << "		||_____// ||    || ||    || ||   V   || \n";
	std::cout << "		||~~~~~\\\\ ||    || ||    || ||       || \n";
	std::cout << "		||     //  \\\\  //   \\\\  //  ||       || \n"; 
	std::cout << "		========    ====     ====   ==       == \n\n\n\n\n";
	
	std::cout << "		You guessed wrong.........\n";
	std::cout << "		You just killed yourself and everyone else in a five block radius.\n";
	
	bPlay = ReplayGame();

	
	
}

void Win()
{
	//This function is for when the player guesses all the codes correctly
	system("CLS");
	std::cout << "		|\\     /|\\__   __/( (    /|( (    /|(  ____ \\(  ____ )\n";
	std::cout << "		| )   ( |   ) (   |  \\  ( ||  \\  ( || (    \\/| (    )| \n";
	std::cout << "		| | _ | |   | |   |   \\ | ||   \\ | || (__    | (____)| \n";
	std::cout << "		| |( )| |   | |   | (\\ \\) || (\\ \\) ||  __)   |     __) \n";
	std::cout << "		| || || |   | |   | | \\   || | \\   || (      | (\\ ( \n";
	std::cout << "		| () () |___) (___| )  \\  || )  \\  || (____/\\| ) \\ \\__ \n";
	std::cout << "		(_______)\\_______/|/    )_)|/    )_)(_______/|/   \\__/ \n\n\n";
	
	std::cout << "	*************************************************************************\n";

	std::cout << "	*			Congradulations Rookie!				* \n";
	std::cout << "	*   You have successfuly defused all the bombs and saved everyone!      * \n";
	std::cout << "	*   You will definitely be getting a promotion and raise for this.	* \n";
	std::cout << "	************************************************************************* \n\n";
	

	bPlay = ReplayGame();
}

int PlayerAdditionCalculations(int First, int Second, int Third)
{
	//This function calculates the player sum of the three numbers for the code sequence
	PlayerSum = First + Second + Third;

	return PlayerSum;
}

int PlayerMultiplicationCalculations(int First, int Second, int Third)
{
	//This function calculates the player product of the three numbers for the code sequence

	PlayerProduct = First * Second * Third;


	return PlayerProduct;
}

int Comparison(int CodeSum, int PlayerSum, int CodeProduct, int PlayerProduct)
{
	//This function compares the sum of the code to the player's sum as well as the product of the code to the player's product
	if ((CodeSum == PlayerSum) && (CodeProduct == PlayerProduct))
	{
		LevelIncrease();
	}
	else
	{
		Boom();
	}

	return 0;
}

bool PlayGame()
{
	//This is the main gameplay function that calls other functions
	srand(time(NULL));
	Opening();
	PlayerInput();
	Comparison(SumCodeTotal, PlayerSum, ProductCodeTotal, PlayerProduct);

	return true;
}

bool ReplayGame()
{
	//This function asks the player if they would like to replay the game
	bool bPlayersChoice = true;
	char PlayerReplay = 0;
	
	std::cout << std::endl;
	std::cout << "		Would you like to play again? ";
	std::cin >> PlayerReplay;
	if ((PlayerReplay == 89) || (PlayerReplay == 121))
	{
		bPlayersChoice = true;
		Difficulty = 1;
	}
	else
	{
		bPlayersChoice = false;
	}

	return bPlayersChoice;
}

void LevelIncrease()
{
	if (Difficulty == MaxDifficulty)
	{
		Win();
	}
	else
	{
		++Difficulty;
	}
}

int RandomNumberGenerator()
{
	int Number = rand()% Difficulty + Difficulty;

	return Number;
}

int MultiplicationCalculations(int First, int Second, int Third)
{
	ProductCodeTotal = First * Second * Third;

	return ProductCodeTotal;
}
4 Likes

Great job! I love it! Can’t wait to see the timer!

I’ll upload it here after the comments once I’m done.
Thanks for the support!

I’ve put a couple of tweaks on the TripleX game. The theme can be described as, “fantasy with slight elements of sci-fi.” I call my version “Menta-X”, although I imagine there are some better names for this.

At first, players only need to enter a two-digit code, but the game progresses to requiring a four-digit code. To counter this, the range of the digits in the code increase half as fast. Here’s the math behind it:

// Declare number code
const int CoordinateA = rand() % ((Difficulty + 1) / 2) + Difficulty;
const int CoordinateB = rand() % ((Difficulty + 1) / 2) + Difficulty;
const int CoordinateC = rand() % ((Difficulty + 1) / 2) + Difficulty;
const int CoordinateD = rand() % ((Difficulty + 1) / 2) + Difficulty;

Players are rewarded with cinematic descriptions as they advance from level to level. However, a certain number of incorrect guesses can result in losing the game, sending them to the beginning of the game.

I also make use of std::cin.get() frequently in the code. This forces the player to press any key to continue.

Here’s the code I wrote for this game (~300 lines). If any of you enjoy the game, let me know what you thought of it. Unfortunately, I couldn’t get beyond level 6. Enjoy!

#include <iostream>
#include <ctime>

void PrintWelcomeMessage()
{
	// Print out the game's title
	std::cout << "-------------------------------------------------------------------------------------------\n\n";
	std::cout << "\t\t  #     #  #####  #   #  #####     #       #   #\n";
	std::cout << "\t\t  ##   ##  #      ##  #    #      ##        # # \n";
	std::cout << "\t\t  # # # #  #####  # # #    #     # #  ####   #  \n";
	std::cout << "\t\t  #  #  #  #      #  ##    #    ####        # # \n";
	std::cout << "\t\t  #     #  #####  #   #    #   #   #       #   #\n";
	std::cout << "\t\t              by Gabriel Hanna                  \n";
	std::cout << "\t\t       Press <Enter> key to continue...         \n\n";
	std::cin.get(); // wait for player to press enter

	// Print out an introductory story message to the players
	std::cout << (char)218 << "-----------------------------------------------------------------------------------------" << (char)191 << "\n";
	std::cout << "| You have found a peculiar trinket made of crystal pulsating with a magical essence.     |\n";
	std::cout << "| Holding it with both hands, your ears ring with echoes from the past.                   |\n";
	std::cout << "| With the power of memory spells, you have the means of finding what lies within.        |\n";
	std::cout << "| Upon touching it, your vision warps. You feel as if you have been transported to a      |\n";
	std::cout << "| strange, new place...                                                                   |\n";
	std::cout << (char)192 << "-----------------------------------------------------------------------------------------" << (char)217 << "\n\n";
	std::cin.get(); // wait for player to press enter

	std::cout << "\t\t     /\\    \n";
	std::cout << "\t\t    /  \\   \n";
	std::cout << "\t\t   /    \\  \n";
	std::cout << "\t\t  /______\\ \n";
	std::cout << "\t\t  |      | \n";
	std::cout << "\t\t  |OOOOOO| \n";
	std::cout << "\t\t  |______| \n";
	std::cout << "\t\t  \\      / \n";
	std::cout << "\t\t   \\    /  \n";
	std::cout << "\t\t    \\  /   \n";
	std::cout << "\t\t     \\/    \n\n";
	std::cin.get(); // wait for player to press enter
}

void PrintLevelIntroduction(int Difficulty)
{
	// Print out an introductory level message to the players
	std::cout << (char)218 << "-----------------------------------------------------------------------------------------" << (char)191 << "\n";
	std::cout << "| You have reached layer " << Difficulty << ".\t                                                          |\n";
	std::cout << (char)192 << "-----------------------------------------------------------------------------------------" << (char)217 << "\n";
}

void PrintMemoryDescription(int LevelDifficulty, int NumberOfFails, bool bLevelCompleted)
{
	// Check if player's guess is correct
	if (bLevelCompleted)
	{
		// Print out a correct-guess message
		std::cout << (char)218 << "-----------------------------------------------------------------------------------------" << (char)191 << "\n";
		std::cout << "| Your vision warps. You delve deeper into the crystal...                                 |\n";
		std::cout << (char)192 << "-----------------------------------------------------------------------------------------" << (char)217 << "\n";

		// Print out a memory sequence as a reward for a correct guess
		// Use tildas for horizontal borders to declare a memory sequence
		if (LevelDifficulty <= 2)
		{
			std::cout << "\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
			std::cout << "\t Standing on a golden shore, you see an island in the distance shrouded in clouds\n";
			std::cout << "\t of pure darkness. Your nostrils fill with the smell of the ocean. Above, the sun\n";
			std::cout << "\t shines down with a blinding radiance.\n";
			std::cout << "\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
		}
		else if (LevelDifficulty == 3)
		{
			std::cout << "\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
			std::cout << "\t In the blink of an eye, you fly across the ocean, touching down on the island.\n";
			std::cout << "\t The charcoal sand feels cold to the touch. A giant, rocky cliff stretches out in\n";
			std::cout << "\t front of you. The sun is nowhere in sight. To your right, you see a glowing\n";
			std::cout << "\t silver necklace with a sapphire jemstone in the center. You pick up the\n";
			std::cout << "\t necklace, slipping it into your pocket. An ornate, obsidian tower with a bridge\n";
			std::cout << "\t looms overhead.\n";
			std::cout << "\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
		}
		else if (LevelDifficulty == 4)
		{
			std::cout << "\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
			std::cout << "\t With phantom speed, you race up the tower's stairways, stopping at a doorway a\n";
			std::cout << "\t hundred feet above the ground. A bridge stretches to a blackened plateau.\n";
			std::cout << "\t Bright, enormous flames engulf a large city, lighting up the darkness. Far away,\n";
			std::cout << "\t the outlines of figures in silver armor surround the town.\n";
			std::cout << "\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
		}
		else if (LevelDifficulty == 5)
		{
			std::cout << "\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
			std::cout << "\t Your vision stretches across the bridge toward the wreckage. Almost instantly,\n";
			std::cout << "\t the flames and soldiers fizzle into smoke. The darkness dissolves, flooding the \n";
			std::cout << "\t island in the light of an orange sunset. A charred city lies in ruins. The\n";
			std::cout << "\t withered remains of a large tree weakly stands at its center. Near the trunk of\n";
			std::cout << "\t the tree is a blurred figure lying horizontally on the ground.\n";
			std::cout << "\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
		}
		else if (LevelDifficulty == 6)
		{
			std::cout << "\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
			std::cout << "\t As you focus on the figure, your surroundings begin to blur and the figure's\n";
			std::cout << "\t details become more defined: purple skin, pointed ears, thin cheekbones, black\n";
			std::cout << "\t eyes with violet irises staring lifelessly into the distance. The figure appears\n";
			std::cout << "\t to be male. His dead arms clutch a book with a leafy texture.\n";
			std::cout << "\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
		}
		else if (LevelDifficulty == 7)
		{
			std::cout << "\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
			std::cout << "\t The book floats from the body, opening up in front of you. Its contents glow a\n";
			std::cout << "\t deep blue and peel off the page. They swirl in midair and rapidly to form a\n";
			std::cout << "\t blurred, blue circle of words written in another language.\n";
			std::cout << "\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
		}
		else
		{
			std::cout << "\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
			std::cout << "\t Everything, including the book, dissolves into a stary night sky. The blue\n";
			std::cout << "\t circle of words spin faster, funneling into your eyes in a blinding light.\n";
			std::cout << "\t You hear the book's words being read aloud by a subconscious voice...\n";
			std::cout << "\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
			std::cin.get(); // wait for player to press enter
			std::cout << "\t\t\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n";
			std::cout << "\t\t\" We should've known we couldn't safe here.                      \"\n";
			std::cout << "\t\t\" They came with blades of sunlight and balls of fire.           \"\n";
			std::cout << "\t\t\" We are outnumbered...                                          \"\n";
			std::cout << "\t\t\"                                                                \"\n";
			std::cout << "\t\t\" No place in this world to hide...                              \"\n";
			std::cout << "\t\t\" Our only true haven is among the stars...                      \"\n";
			std::cout << "\t\t\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n";
			std::cin.get(); // wait for player to press enter
			std::cout << "\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
			std::cout << "\t The stars in the black void align, connecting to form a stellar map with glowing\n";
			std::cout << "\t strands vibrating in the dark. This diagram fades as your vision returns and you\n";
			std::cout << "\t find yourself staring down at the crystal.\n";
			std::cout << "\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
		}
	}
	else
	{
		if (NumberOfFails <= 1)
		{
			// Print a 1st-level, incorrect-guess message
			std::cout << (char)218 << "-----------------------------------------------------------------------------------------" << (char)191 << "\n";
			std::cout << "| You hear a faint humming noise gradually fade.                                          |\n";
			std::cout << (char)192 << "-----------------------------------------------------------------------------------------" << (char)217 << "\n";
		}
		else if (NumberOfFails == 2)
		{
			// Print a 2nd-level, incorrect-guess message
			std::cout << (char)218 << "-----------------------------------------------------------------------------------------" << (char)191 << "\n";
			std::cout << "| Your vision begins to blur. You feel the echoes slip away.                              |\n";
			std::cout << (char)192 << "-----------------------------------------------------------------------------------------" << (char)217 << "\n";
		}
		else
		{
			// Print a maximum incorrect-guess message, indicating that the game has reset
			std::cout << (char)218 << "-----------------------------------------------------------------------------------------" << (char)191 << "\n";
			std::cout << "| You wake from the slur of memories looking down at the crystal in your hands.           |\n";
			std::cout << (char)192 << "-----------------------------------------------------------------------------------------" << (char)217 << "\n";
		}
	}

	std::cin.get(); // wait for player to press enter
}

bool PlayGame(int Difficulty)
{
	PrintLevelIntroduction(Difficulty);

	// 
	// Diff | # Coordinates | Range
	// -----+---------------+------------
	// 1    | 2             | 2-3
	// 2    | 2             | 2-3
	// 3    | 3             | 3-5
	// 4    | 3             | 3-5
	// 5    | 3             | 4-7
	// 6    | 4             | 4-7
	// 7    | 4             | 5-9

	int NumCoordinates;
	if (Difficulty == 1 || Difficulty == 2)
		NumCoordinates = 2;
	else if (Difficulty == 3 || Difficulty == 4 || Difficulty == 5)
		NumCoordinates = 3;
	else
		NumCoordinates = 4;

	// Declare number code
	const int CoordinateA = rand() % ((Difficulty + 1) / 2) + Difficulty;
	const int CoordinateB = rand() % ((Difficulty + 1) / 2) + Difficulty;
	const int CoordinateC = rand() % ((Difficulty + 1) / 2) + Difficulty;
	const int CoordinateD = rand() % ((Difficulty + 1) / 2) + Difficulty;

	int CoordinateSum;
	int CoordinateProduct;

	// Only use the number of coordinates appropriate to that difficulty
	if (NumCoordinates == 2)
	{
		CoordinateSum = CoordinateA + CoordinateB;
		CoordinateProduct = CoordinateA * CoordinateB;
	}
	else if (NumCoordinates == 3)
	{
		CoordinateSum = CoordinateA + CoordinateB + CoordinateC;
		CoordinateProduct = CoordinateA * CoordinateB * CoordinateC;
	}
	else
	{
		CoordinateSum = CoordinateA + CoordinateB + CoordinateC + CoordinateD;
		CoordinateProduct = CoordinateA * CoordinateB * CoordinateC * CoordinateD;
	}

	// Print number of coordinates, sum, and product to the terminal
	std::cout << "~ The next memory gate has coordinates using " << NumCoordinates << " digits.\n";
	std::cout << "~ The individual coordinates add up to " << CoordinateSum << ".\n";
	std::cout << "~ The individual coordinates multiplied together equal " << CoordinateProduct << ".\n";
	std::cout << "\n";
	
	// Store player guess
	int GuessA = 1, GuessB = 1, GuessC = 1, GuessD = 1;
	int GuessSum, GuessProduct;

	std::cout << "> ";
	
	// Only ask for the number of coordinates appropriate to that difficulty
	if (NumCoordinates == 2)
	{
		std::cin >> GuessA >> GuessB;
		GuessSum = GuessA + GuessB;
		GuessProduct = GuessA * GuessB;
	}
	else if (NumCoordinates == 3)
	{
		std::cin >> GuessA >> GuessB >> GuessC;
		GuessSum = GuessA + GuessB + GuessC;
		GuessProduct = GuessA * GuessB * GuessC;
	}
	else
	{
		std::cin >> GuessA >> GuessB >> GuessC >> GuessD;
		GuessSum = GuessA + GuessB + GuessC + GuessD;
		GuessProduct = GuessA * GuessB * GuessC * GuessD;
	}

	// Return whether or not the player's guess is correct
	return (GuessSum == CoordinateSum && GuessProduct == CoordinateProduct);
}

void PrintGameCompletedMessage()
{
	std::cout << (char)218 << "-----------------------------------------------------------------------------------------" << (char)191 << "\n";
	std::cout << "| As your mind touches the core of the crystal, it is imprinted with the secrets of a     |\n";
	std::cout << "| forgotten civilization. Now, it is up to you to preserve them.                          |\n";
	std::cout << (char)192 << "-----------------------------------------------------------------------------------------" << (char)217 << "\n";
	std::cin.get(); // wait for player to press enter
}

void SeedRandomizer()
{
	srand(time(NULL));
}

int main()
{
	PrintWelcomeMessage();

	int LevelDifficulty = 1;
	int NumberOfFails = 0;
	const int MaxLevel = 7;
	const int MaxFails = 3;

	while (LevelDifficulty <= MaxLevel) // loop until all levels completed
	{
		SeedRandomizer();
		bool bLevelComplete = PlayGame(LevelDifficulty);
		std::cin.clear();		// clears any errors
		std::cin.ignore();		// discards the buffer

		if (bLevelComplete)
		{
			++LevelDifficulty;	// advance to the next level

			// print a description of the memory seen
			PrintMemoryDescription(LevelDifficulty, NumberOfFails, bLevelComplete);

			NumberOfFails = 0;	// reset any previous fails
		}
		else
		{
			++NumberOfFails;	// increment number of fails

			// print a description of the memory seen
			PrintMemoryDescription(LevelDifficulty, NumberOfFails, bLevelComplete);

			if (NumberOfFails >= MaxFails)	// if max fails hit or exceeded, reset game
			{
				LevelDifficulty = 1;
				NumberOfFails = 0;
			}
		}
	}

	PrintGameCompletedMessage();

	return 0;
}
3 Likes

Awesome work!!

@RynEllis Nice ASCII art! It’s a nice advancement of the TripleX game.

I also liked seeing the function declarations at the top.

Out of curiosity, how far did you get?

1 Like

Privacy & Terms