Triple X - Taming rand()

15_tx_uc2
#1

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:

1 Like
#2

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;
}
1 Like
#3

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();
}
2 Likes
#4
#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;
}
1 Like
#5

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;
}
1 Like
#6

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

#7

Awesome Job!

1 Like
#8

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
#9

Great work!

#10

Thx allot.

#11
#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
#12

#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

#13

#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!

#14

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;
}