Triple X - Taming rand()

@G1HannaMax I put the functions at the beginning of the program because it lets the compiler know before anything is called that they are there. It was something I was taught in college when I took C programming. It just stuck and that’s what I do now.

As for how far I got, I have changed the opening screen to have the title but prompt the user for their name and changed things up a bit so their name is displayed next to the rookie part. I also changed the win() to include there name as well. I have started to get the file writing part done. I have gotten it to make a new file if there isn’t a high score text file and to append the new name and score below the last.

I also plan on changing the opening screen so it just has the title, the option to start the game, high score, and to exit immediately.

I haven’t started on getting the timer to go. I’m a bit stumped on that one. I have found tutorials on how to do them but I haven’t delve deep into that one yet. I will be over the next day or so (life has been busy lol).

Thanks for checking it out. I greatly appreciate it!

@Kevin-Brandon & @G1HannaMax so after reading and reading and reading, there isn’t apparently a way to have a countdown clock while waiting for input from the user. So I unfortunately have to scrap that idea. I do plan on making a version of this with Unreal so I’ll do it there as I know from when I was coding in Unity, there is multiple options to have things doing their own thing simultaneously.

I am working to perfect the file out and a title screen. I have figured out how to change the text colour on the screen as well.

Yeah I didn’t think it was possible but you never know. That would be cool seeing it in a Unreal. Maybe you an create a floating terminal. I can’t wait to see what you come up with!

Finally done. (well for now until I decide to do something else different with it…we’ll see)

I have changed how the game opens. Now there is a menu to choose to either start the game, display the high score, or exit the game.
The game will proceed as normal if you select start game. If you enter the choice for high score, the screen will clear, display the title, and then pull the highscore.txt if it exists, and if it doesn’t, the program will terminate. If you select to leave the game, the game will terminate immediately.
When playing the game, the player will be prompt to enter there name, and the story is catered to that person thereafter. When the player either wins the game or loses the game, the high score will be saved in highscore.txt (which it will create if it is not tested).

//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>
#include <string>
#include <fstream>
#include <cstdlib>



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();														//Generates random numbers for the code
void PlayerIntroduction();															//To get player's first name to use in the game
void Title();																		//To print the main title of the game
int MainScreen();																	//Main Screen
void HighscoreDisplay();															//Display high score
void WriteHighScore();																//Write high score






//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 };
string PlayerName;
//High Score File Information
ifstream inFile;




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


//Functions
int RandomNumberGenerator()
{
	//This function randomizes the number for the code
	int Number = rand() % Difficulty + Difficulty;

	return Number;
}

int MainScreen()
{
	char Choice = 0;
	Title();
	std::cout << "	************************************************************************************************* \n";
	std::cout << "	*				1.	Start Game						*\n";
	std::cout << "	*				2.	High Score						*\n";
	std::cout << "	*				X.	Exit Game						*\n";
	std::cout << "	************************************************************************************************* \n";

	std::cout << "					Pick an option: ";
	std::cin >> Choice;

	if (Choice == '1')
	{
		PlayGame();
	}
	else if (Choice == '2')
	{
		HighscoreDisplay();
	}
	else
	{
		exit(0);
	}


	return 0;
}

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

	return true;
}

void Title()
{
	//This function prints the title of the game to the screen
	system("CLS");
	system("color 1");
	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";


}

void Opening()
{

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

	
	if (Difficulty == 1)
	{
		PlayerIntroduction();
	}
	
	Title();


	std::cout << "	************************************************************************************************* \n";
	if (Difficulty == 1)
	{
		std::cout << "	*  Rookie " << PlayerName << ", you are our only bomb defuser.							*\n";
		std::cout << "	*  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 " << PlayerName << "! 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 MultiplicationCalculations(int First, int Second, int Third)
{
	//This function calculates the product for the randomized code
	ProductCodeTotal = First * Second * Third;

	return ProductCodeTotal;
}

void PlayerIntroduction()
{
	//This function prompts the user for their name
	std::cout << "	************************************************************************************************* \n";
	std::cout << "	**********************  Hey YOU! Rookie!  What's your name?  ************************************\n ";
	std::cout << "						";
	std::cin >> PlayerName;


}

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

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 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;
	//checking to see if Y or y was selected in ASCII
	if ((PlayerReplay == 89) || (PlayerReplay == 121))
	{
		bPlayersChoice = true;
		Difficulty = 1;
	}
	else
	{
		bPlayersChoice = false;
	}

	return bPlayersChoice;
}

void LevelIncrease()
{
	//This function either increases the difficulty per level or sends the program to the win function if the difficult level is reached
	if (Difficulty == MaxDifficulty)
	{
		Win();
	}
	else
	{
		++Difficulty;
	}
}

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";
	
	
	WriteHighScore();
	
	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 " << PlayerName << "!			* \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";

	WriteHighScore();
	bPlay = ReplayGame();
}

void HighscoreDisplay()
{
	int Increments = 0;
	char Character = '#';

	Title();

	ifstream Myfile("highscore.txt", ios::in);

	if (!Myfile)
	{
		std::cout << "Error opening file.  Program will terminate.";
		exit(0);
	}

	std::cout << "					     High Score\n";
	std::cout << "				*****************************************\n";
	std::cout << "				*	Name		Level		*\n";
	std::cout << "				*****************************************\n";

	for (Increments = 0; !Myfile.eof(); Increments++)
	{
		if (Character == '#')
		{
			std::cout << "					";
		}
		Myfile.get(Character);
		std::cout << Character;
		if (Character == '\n')
		{
			std::cout << "					";
		}
	}

	Myfile.close();
	system("pause");
	
}

void WriteHighScore()
{
	ofstream Myfile("highscore.txt", ios::app);

	if (!Myfile)
	{
		std::cout << "Error. Program closing." << std::endl;
		exit(0);
	}

	Myfile << PlayerName << "		" << Difficulty << "\n";
	Myfile.close();

}


4 Likes

That is awesome that the story catchers to the player’s name. You are giving me good ideas to try! You did an awesome job!

This section was enjoyable, finally getting to play the game was fun.
My game got difficult at level 4, I set my max difficulty to 5, so I got a bit stuck at level 4.
It will be interesting to see how difficult it really gets if I increased the max difficulty.
Just one question, I noticed when I enter the wrong code, after the game restarts the hints randomize rather than display the same thing. I’m wondering if there is a way to leave it the same if you get it wrong and then continue to be random after getting the correct code.
Here’s my code so far, after this section:

#include <iostream>
#include <ctime>

void PrintIntroduction(int CodeProduct, int CodeSum, int LevelDifficulty)
{   
    //print introduction/menu to the user
    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";
    std::cout << "You're a whistle-blower hacking into the CEO's computer,\n";
    std::cout << "hack the LEVEL " << LevelDifficulty << " security code to retrieve the evidence...\n\n";
    std::cout << "Here's the information you know about the security codes...\n";
    std::cout << "  * There are three numbers in the codes\n";
    std::cout << "  * The codes multiply to give " << CodeProduct << "\n";
    std::cout << "  * The codes add-up to " << CodeSum << "\n\n";
    std::cout << "Enter the correct code to continue.\n";
}

bool PlayGame(int LevelDifficulty)
{
    //declare int variables to use for the three numbered code
    const int CodeA = rand() % LevelDifficulty + LevelDifficulty;
    const int CodeB = rand() % LevelDifficulty + LevelDifficulty;
    const int CodeC = rand() % LevelDifficulty + LevelDifficulty;

    //declare int variables to hold sum, prod, div, and mod calculations
    const int CodeSum = CodeA + CodeB + CodeC;
    const int CodeProduct = CodeA * CodeB * CodeC;

    PrintIntroduction(CodeProduct, CodeSum, LevelDifficulty);

    //store player gues
    int GuessA, GuessB, GuessC;
    std::cin >> GuessA >> GuessB >> GuessC;

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

    //check if the players guess is correct
    if ((GuessSum == CodeSum) && (GuessProduct == CodeProduct)) 
    {
        std::cout << "****Success! Continue on to the next level!****\n";
        return true;
    }
    else
    {
        std::cout << "**** Wrong code! Try again, you can do this!****\n";
        return false;
    }
}

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

    int LevelDifficulty = 1;
    const int MaxLevel = 5;

    while (LevelDifficulty <= MaxLevel) //loop the game until all levels are completed
    {
        //std::cout << rand() % 2 << "\n"; //returns mod value - 1 **note**
        bool bLevelComplete = PlayGame(LevelDifficulty);
        std::cin.clear(); //clears any errors
        std::cin.ignore(); //discards the buffer

        if (bLevelComplete)
        {
            ++LevelDifficulty;
        }
    } 

    std::cout << "Amazing job, you made it through all of the security levels! Now download the files and get out quick! This guy is going down!\n";

    return 0;
}
//# symbol is used for preprocessor directive to include libraries
#include <iostream>
#include <ctime>

void PrintInstroduction(int Difficulty)
{  
    std::cout << "Imagine you are walking in the middle of the night in a level " << Difficulty << " dark alley and someone came to you..." << std::endl;
    std::cout << "They say - Solve this math problem or you won't live  another day...\n";
}

bool PlayGame(int Difficulty)
{
    PrintInstroduction(Difficulty);    
    //Declaration statements
    const int CodeA = rand() % Difficulty + Difficulty; //Difficulty + Difficulty removes 0s from possible values
    const int CodeB = rand() % Difficulty + Difficulty; //Difficulty + Difficulty removes 0s from possible values
    const int CodeC = rand() % Difficulty + Difficulty; //Difficulty + Difficulty removes 0s from possible values

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

    //Exprsion statements
    std::cout << std::endl;
    std::cout << "#There are 3 numbers in the code" << std::endl;
    std::cout << "#The codes add-up to: " << CodeSum << std::endl;
    std::cout << "#The codes multiply to give: " << CodeProduct << std::endl;

    //Store player guess
    int GuessA, GuessB, GuessC;
    std::cin >> GuessA >> GuessB >> GuessC; //Character input
    std::cout << std::endl;
   
    int GuessSum = GuessA + GuessB + GuessC;
    int GuessProduct = GuessA * GuessB * GuessC;

    //Check player guess
    if (GuessSum == CodeSum && GuessProduct == CodeProduct)
    {
        std::cout << "#You win! Go to next level: " << Difficulty << std::endl; 
        return true;
    }
    else 
    {
        std::cout << "#You didn't solve the problem. Retry level: " << Difficulty << std::endl;
        return false;
    }
}

int main()
{
    srand(time(NULL));//Creates random secunce based on the time of day

    int LevelDifficulty = 1;
    const int MaxLevel = 5;

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

        if (bLevelComplete)
        {    
            ++LevelDifficulty;
        }       
    }

    std::cout << "\n#Congratulations, you have completed all levels. You will live!\n";
    //Return statement
    return 0;
}
1 Like

Thanks a lot for this cool introduction! I’m familiar with other programming languages, but i’ve never seen a better introduction than this one!

1 Like
#include <iostream>
#include<ctime>
#include<cstdlib>
#include<windows.h>

using namespace std;
void Intro()
{

cout<<endl<<" -->>THE GAME BEGINS.............EITHER DIE OR WIN AND LIVE LIVE A KING"<<endl;
cout<<"-->>guess the correct combination of three digit which is from 1 to 9 AND ##WIN THE TREASURE##"<<endl;
cout<<"-->>you will get only 3 continuous chances to fail.......play wisely and clear ALL 5 LEVELS\n";

}
void Desc(int Diff);
bool Test(int Diff,int & RemChance)
{
    cout<<"==========================================================="<<endl;
    cout<<"THIS IS LEVEL "<<Diff;
    cout<<"\n===========================================================\n";
    int a[3],b[3],OrigSum=0,OrigProduct=1,GuessSum=0,Guessproduct=1;
    a[0]=(rand() % Diff) + (Diff*2);
    a[1]=(rand() % Diff) + (Diff*3);
    a[2]=(rand() % Diff) + (Diff);

    for(int i =0;i<3;i++)
    {
        OrigSum=OrigSum+a[i];
        OrigProduct=OrigProduct*a[i];
    }
    cout<< "+ There are 3 numbers in the code";
    cout << "\n+ The codes add-up to: " << OrigSum;
    std::cout << "\n+ The codes multiply to give: " << OrigProduct <<endl;
    for(int i =0;i<3;i++)
    {
        cin>>b[i];
        Beep(1000,500);
       GuessSum=GuessSum+b[i];
        Guessproduct=Guessproduct*b[i];
    }
    if(OrigProduct==Guessproduct && OrigSum==GuessSum)
    {
        cout<<"\nCONGO............!!!!!   YOU WON THIS LEVEL"<<endl;
        return (true);
    }
    else
    {   ++RemChance;
        cout<<"\nOOOPPPPSSSS ............!!!! YOU LOST"<<endl;
        Beep(1000,1500);

        return(false);
    }
}
int main()
{
    Intro();
    srand(time(NULL));
    bool Result;
    int MinDiff=1,RemChance=0;
    const int MaxDiff=5;
    while(MinDiff<=MaxDiff && RemChance!=3)
    {
        Result=Test(MinDiff,RemChance);
        cin.clear();
        cin.ignore();
       if(Result)
       {
           ++MinDiff;
       }
    }
    if(RemChance==3)
    {
        cout<<"You exceded you maximum trial limit"<<endl;
        return 0;
    }
    else if (MinDiff == MaxDiff)
    {
        cout<<"YOU WON WHOLE ROUND"<<endl;
    }
    return 0;
}

i have put a extra constraint that you can fail maximum 3 times in whole game.and i have also added beep sound to make you feel like a live system …

Thank you,
DB

1 Like

Impressive work!

/* std::endl; can be used at the end of a code or \n;
\n can not be added on the end of a variable name but
can be added at the beginning of strings or lines to
add end of line or line of space before your string or line*/

#include
#include

void PrintIntroduction(int Difficulty)
{
// Games story intro
std::cout << “\n\nYour a Competitive Gamer breaking codes for a 1 in 10 chance to compete in a world tournament, welcome to Round " << Difficulty;
std::cout << std::endl;
std::cout << " Enter the correct code answers to advance and be the first to win your spot”;
}

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;

/* <starting with this, this is what is used to
write a multi line comment and this is what is used
to end it> */

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

// Print sum & product to terminal
std::cout << std::endl;
std::cout << std::endl;
std::cout << "+ There are 3 numbers in the code"  << std::endl;
std::cout << "+ The codes add-up to:" << CodeSum << std::endl;
std::cout << "+ The codes multiply to give:" <<  CodeProduct << std::endl;

int GuessA, GuessB, GuessC;

std::cin >> GuessA >> GuessB >> GuessC;
std::cout << "You Entered: " << GuessA << GuessB << GuessC;

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

std::cout << std::endl;
std::cout << std::endl;
std::cout << "Your Guess codes add-up to: " << GuessSum << std::endl;
std::cout << "Your Guess codes multiply to give: " <<  GuessProduct << std::endl; 
std::cout << std::endl;

if (GuessSum == CodeSum && GuessProduct == CodeProduct)
{
    std::cout << "You Win This Round!";
    return true;
}
else
{
    std::cout << "You Lose!";
    return false;
}

}

int main()
{
srand(time(NULL)); // create new random sequences based on time of day
int LevelDifficulty = 1;
int const MaxDifficulty = 13;

while (LevelDifficulty <= MaxDifficulty) // loops game till at max level
{
    bool bLevelComplete = PlayGame(LevelDifficulty);
    std::cin.clear(); //clears any errors, needed to stop loop (repeating itself over n over in a broken manner) 
    std::cin.ignore(); // Discards the Buffer, also needed to stop loop (repeating itself over n over in a broken manner) 

    if (bLevelComplete)
    {
        ++LevelDifficulty;
    }
    

}
std::cout << "\n*** You have Successfully Completed all rounds you WIN!!!  ***\n";

return 0;

}

This is my completed game first one was a good learning experience

Just finished! Super excited that it works just how I intended. My code is a bit modified from the instruction in a few ways. First, it’s single elimination. If you’re wrong once, game over. Second, I added some delays in the printouts, mostly just because I like the optics of it as opposed to everything printing immediately. I moved a few of the print sections to their own functions just to clean up the code a bit. Lastly, I used a fixed mod for setting difficulty but bumped the range up. I found that it was easy in the first levels and forced me to really sit and think on the last 2, which is exactly how I wanted it.

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

using namespace std::this_thread;
using namespace std::chrono;

void PrintIntroBlock()
{
   // Prints the one-time intro message to the terminal
   std::cout << "\n---------------------------------------------\n\nHello Mr Pink.\n"; sleep_for(seconds(2));
   std::cout << "We have received your instructions.\n"; sleep_for(seconds(2));
   std::cout << "The package is set to drop at the coordinates\n"; sleep_for(seconds(2));
}

void PrintInstructions(int Difficulty, int PrintCodeSum, int PrintCodeProduct)
{
   // Print the instructions and hints to the terminal every loop
   std::cout << "\n---------------------------------------------\n";
   std::cout << "Level " << Difficulty << " security clearance confirmed."; 
   std::cout << "\n---------------------------------------------\n\n";sleep_for(seconds(3));
   std::cout << "Please enter your code sequence to confirm:\n"; sleep_for(microseconds(100000));
   std::cout << "+ There are 3 numbers in the code (";
   std::cout << Difficulty << " - " << Difficulty + 5 << ")\n"; sleep_for(microseconds(100000));
   std::cout << "+ The 3 numbers add up to " << PrintCodeSum << "\n"; sleep_for(microseconds(100000));
   std::cout << "+ The 3 numbers multiply to give " << PrintCodeProduct << "\n"; sleep_for(microseconds(100000));
   std::cout << "\nEnter the three single-digit numbers, each followed by 'SPACE', then confirm with 'ENTER'\n";
}

void PrintWinGameBlock()
{
   // Prints the one-time win message to the terminal
   std::cout << "\n\n\nIt's been a pleasure Mr. Pink.\n"; sleep_for(seconds(2));
   std::cout << "\nOperation is go.\n"; sleep_for(seconds(2));
   std::cout << "\nSee you on the other side.\n\n\n\n"; sleep_for(seconds(2));
}

void PrintLoseGameBlock()
{
   // Prints the one-time lose message to the terminal
   std::cout << " << ACCESS DENIED \n"; sleep_for(seconds(1));
   std::cout << "\nYou are not the true Mr. Pink.\n"; sleep_for(seconds(1));
   std::cout << "Force termination in \n"; sleep_for(microseconds(2000000));
   std::cout << "3\n"; sleep_for(microseconds(500000));
   std::cout << "2\n"; sleep_for(microseconds(500000));
   std::cout << "1\n"; sleep_for(microseconds(500000));
}

bool PlayGame(int Difficulty)
{
   // Declare the 3 number code, and their sum and product
   int CodeOne = Difficulty + (rand() % 5);
   int CodeTwo = Difficulty + (rand() % 5);
   int CodeThree = Difficulty + (rand() % 5);
   int CodeSum = CodeOne + CodeTwo + CodeThree;
   int CodeProduct = CodeOne * CodeTwo * CodeThree;

   PrintInstructions(Difficulty, CodeSum, CodeProduct);

   // Take user inputs
   int PlayerGuessOne, PlayerGuessTwo, PlayerGuessThree;
   std::cin >> PlayerGuessOne;
   std::cin >> PlayerGuessTwo;
   std::cin >> PlayerGuessThree;
   int PlayerGuessSum = PlayerGuessOne + PlayerGuessTwo + PlayerGuessThree;
   int PlayerGuessProduct = PlayerGuessOne * PlayerGuessTwo * PlayerGuessThree;
   
   
   std::cout << "\n---The sum of your code sequence is: " << PlayerGuessSum;
   //Determines if the answer is correct
   if (PlayerGuessSum == CodeSum)
   {
       std::cout << " << VERIFIED\n"; sleep_for(seconds(1));
       std::cout <<"---The product of your code sequence is: " << PlayerGuessProduct;
       if (PlayerGuessProduct == CodeProduct)
       {
           // both sum and product are correct
           std::cout << " << VERIFIED\n"; sleep_for(seconds(1));
           std::cout << "SUCCESS: Your coordinates have been transmitted.\n"; sleep_for(seconds(2));
           return true;
       }
       else
       {
           // sum is correct, product is incorrect
           PrintLoseGameBlock();
           return false;
       }
   }
   else
   {
       // sum is incorrect
       PrintLoseGameBlock();
       return false;
   }
}

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

   PrintIntroBlock();
   
   int LevelDifficulty = 1;
   while (LevelDifficulty <= 5) //loop the game until the max level
   {
       bool bLevelComplete = PlayGame(LevelDifficulty);
       std::cin.clear(); std::cin.ignore(); // Clears errors, discards the buffer

       if (bLevelComplete)
       {
           if (LevelDifficulty == 5)
           {
               PrintWinGameBlock();
           } 
           ++LevelDifficulty; //increases the level if correct
       }
       else
       {
           LevelDifficulty = 6; //forces end of loop if false
       }  
   }

   return 0;
}
1 Like

Well the coding part went out to be easy but the Game is really Tough
The logic is same but the story-line is a bit different

#include <iostream>
#include <ctime>

void Intro (int Difficulty)
{
    std::cout<<"\n\nAnswer this question to get past Door "<<Difficulty<<" in the Maze\n";
}

bool PlayGame(int Difficulty)
{
    Intro(Difficulty);
    srand(time(NULL));
    int CodeA = rand() % Difficulty + Difficulty;
    int CodeB = rand() % Difficulty + Difficulty;
    int CodeC = rand() % Difficulty + Difficulty;
    int CodeSum = CodeA + CodeB + CodeC;
    int GuessA,GuessB,GuessC,GuessSum,GuessProduct;
    int CodeProduct = CodeA * CodeB * CodeC;
    std::cout<<"Give me 3 Numbers whose Sum is "<<CodeSum<<" and Product is "<<CodeProduct<<std::endl;
    std::cin>>GuessA>>GuessB>>GuessC;
    GuessSum=GuessA+GuessB+GuessC;
    GuessProduct=GuessA*GuessB*GuessC;
    if(GuessSum==CodeSum&&GuessProduct==CodeProduct)
    {
        std::cout<<"Argh! I am the Math Monster, You Cannot Escape Me\n";
        return true;
    }
    else
    {
        std::cout<<"Ahh HaaHaaHaa! I will not let you Finish Me!\n";
        return false;
    }
}

int main()
{
    std::cout<<"\n\n*You are being HAUNTED every day by the MATH MONSTER\n*It has now come face-to-face to Challenge you\n*It has put you in a Maze of 10 Levels\n*You need to answer the questions it asks to beat each level\n*Use this Oppertunity to beat and overcome it for the rest of your life!\n";
    int Difficulty=1;
    const int MaxDifficulty=10;
    while(Difficulty<=MaxDifficulty)
    {                
        if(PlayGame(Difficulty))
        {        
            Difficulty++;
        }
        std::cin.clear();
        std::cin.ignore();
    }
    std::cout<<"\nOhhh Noooooooo! What is Happening! Nooooooooooooooooooooooooooooooooooo...";
    std::cout<<"\n\nHURRAY! You Deafeated the Math Monster. You Should be proud of yourself!";
    return 0;
}
1 Like

Awesome work!

2 Likes

Nothing is more scary than the math monster!

2 Likes

This is great! Blown away, one day I hope to be this adventurous with my code… long way off yet!

2 Likes
Where am I...? Am I trapped?
There's a Level 5 code... Let's crack it.

+ There are 3 numbers in the code
+ The codes add up to: 18
+ The codes multiply to give: 210
Enter 3 numbers: 5 6 7
You Entered: 5 6 7
You got out!

You foiled the Math Wiz's revenge!

Actually failed the Level 5 code once because I forgot about the sum portion haha.

I tried Simplicity while making this :slight_smile: as i am a veteran programmer i made this without much reference from the videos so some functions might differ!

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

int Score=2;

void PrintIntroduction()
{
    std::cout<<"You are a Secret agent!\n You need to break into the master server by providing a key code:\n";
    std::cout<<"Enter the Correct code to continue:\n";
    std::cout<<"\n\n Current Score:"<<Score;
}


void PlayGameAtDifficulty(int difficulty)
{
    PrintIntroduction();
    int CodeA = rand() % Score + Score;
    int CodeB = rand() % Score + Score;
    int CodeC = rand() % Score + Score;
    int GuessA, GuessB, GuessC;
    int CodeSum=CodeA+CodeB+CodeC;
    int CodeProduct=CodeA*CodeB*CodeC;
    int GuessSum,GuessProduct;

    std::cout<<"\nThere are three digits in the code.\n";
    std::cout<<"\nThe Code Adds Up To:"<<CodeSum;
    std::cout<<"\nThe Digits Multiply to give:"<<CodeProduct;

    std::cout<<"\nEnter Digit one:";
    std::cin>>GuessA;
    std::cout<<"\nEnter Digit two:";
    std::cin>>GuessB;
    std::cout<<"\nEnter Digit Three:";
    std::cin>>GuessC;

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

    if(GuessSum == CodeSum && GuessProduct == CodeProduct)
    {
        std::cout<<"\nYOU WIN!";
        Score++;
        getchar();
    }
    else
    {
        std::cout<<"\nYOU LOOSE";
        Score--;
        getchar();
    }
    

}


int main()
{
    srand(time(NULL));
    
    int difficulty=2;
    int const maxdifficulty=10;
   
    while(difficulty <= maxdifficulty)
    {
        system("clear");   //Clears the screen
        PlayGameAtDifficulty(difficulty);
        std::cin.clear(); //clears the fail bit
        std::cin.ignore(); //discards the buffer
        if (Score==difficulty)
        {
            ++difficulty;  //increases the difficulty if score increases
        }
        if (Score<1)
        break; 
         
        system("clear");
    }

    if(Score==maxdifficulty)
    {
        std::cout<<"\nWOW... You are now a master hacker!!\n";
        getchar(); //Just to give a slight pause before exit
    }
    else
    {
        std::cout<<"\n You need a lot of practice"; 
        getchar();
    }
    
    
    
    return 0;

}

1 Like

Final Game. I had tell myself that it was completed or else I would’ve kept messing with it. Thank you for helping me learn this!

#include <iostream>
#include <ctime>

 void PrintIntroduction(int Difficulty)
{
std::cout << "\n\nWelcome to...\n\n";

std::cout << "#######                               #     #\n";
std::cout << "   #    #####  # #####  #      ######  #   #\n";  
std::cout << "   #    #    # # #    # #      #        # #\n";   
std::cout << "   #    #    # # #    # #      #####     #\n";    
std::cout << "   #    #####  # #####  #      #        # #\n";   
std::cout << "   #    #   #  # #      #      #       #   #\n";  
std::cout << "   #    #    # # #      ###### ###### #     #\n\n"; 

//Begining of story- Sets the mood.
std::cout << "It's a level " <<Difficulty;
std::cout << " trap! They may have gotten you this time, but you're about to show them why you are a 'MASTER HACKER'...\n
If you can hack the system, you can escape with your freedom...\n\n";
}

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

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


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

//Print CodeSum and CodeProduct to the Terminal
std::cout << "+There are 3 digits in the code...";
std::cout << "\n+The code adds up to: " <<CodeSum;
std::cout << "\n+The code multiplied together equal: " << CodeProduct <<std::endl;


int GuessA, GuessB, GuessC;
std::cin >> GuessA >> GuessB >> GuessC;


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

//Check if player guess is correct

if (GuessSum == CodeSum && GuessProduct == CodeProduct)
{
    std::cout << "\nThat's It! You're almost there!\n";
    return true;
}
else
{
    std::cout << "\nUmmm... That is not correct... Try again, dummy!";
    return false;
}


}

int main()

{   srand(time(NULL));
    int LevelDifficulty =1;
    const int MaxDifficulty = 5;

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

    if (bLevelComplete)
    {
        ++LevelDifficulty;
    }
    
}
    std::cout << "\nYou've hacked the system and you're free! Great Job!\n";
return 0;
}

Gavin, thanks a lot for this brilliant section, i really learnt a lot of c++(or at least i see it as much, compared to that which i kenw before). I’m really happy with my final game, although i didn’t really do ASCII xd. Here are my results:

#include <iostream>
#include <ctime>

void PrintIntroduction(int Difficulty)
{
    std::cout << "\n\nYou're imprisoned within an alien ship, where you've been tortured for several days. Out of the blue, one of the guards comes to you. He says he'll set you free and even give you access to an escape capsule, in order to warn mankind about the upcoming invasion, on one condition; For him to know you're smart enough to use one of the capsules properly, you must answer correctly to some math riddles... ";
    std::cout << "\n"; 
    std::cout << "\nThe riddle number " << Difficulty << " goes as follows...";
}

bool PlayGame(int Difficulty)
{
    PrintIntroduction(Difficulty);
    
    // NumberC = 0; 

    
    const int NumberA = rand() % Difficulty + Difficulty;
    const int NumberB = rand() % Difficulty + Difficulty;
    int NumberC;
    NumberC = rand() % Difficulty + Difficulty;

    // NumberB = 13;

    //NumberA=1; 

    int SumABC = NumberA + NumberB + NumberC;
    int ProdABC = NumberA * NumberB * NumberC;

    // NumberA=1; 

    //print the prod and addition to the cmd
    std::cout << "\n";
    std::cout << "There were 3 numbers..." << "\n";
    std::cout << "Those numbers add-up to: " << SumABC << "\n";
    std::cout << "Those numbers multiply to: " << ProdABC << "\n";
    
    int GuessA, GuessB, GuessC;
    std::cin >> GuessA >> GuessB >> GuessC;
    //std::cin >> GuessB;
    //std::cin >> GuessC;
    //std::cout << GuessA << GuessB << GuessC;
    
    int SumGuess = GuessA + GuessB + GuessC;
    int ProdGuess = GuessA * GuessB * GuessC;

    if(SumGuess == SumABC && ProdGuess == ProdABC)
    {
        std::cout << "You've nailed it!";
        return true;
    }
    else
    {
        std::cout << "You've lost and are forever doomed to see youself rott and your species perish from within your cell";
        return false;
    }
    
    //std::cout << SumGuess;
    //std::cout << ProdGuess;
}

int main()
{
    srand(time(NULL));
    int LevelDifficulty = 1;
    int const MaxLevel = 7;
    while(LevelDifficulty <= MaxLevel)
    {
        //std::cout << rand() % 11 << "\n";
        bool bLevelCompleted = PlayGame(LevelDifficulty);
        //PlayGame();
        std::cin.clear();
        std::cin.ignore();

        if(bLevelCompleted)
        {
            ++LevelDifficulty;
        }
        else
        {
            //break;
            //LevelDifficulty = MaxLevel + 1;
            return 0;
        }
        
    }
    std::cout << "\nYou've succesfully completed all the riddles!, you're now free to go save humanity";
    //signal that everything ran as planned :)
    return 0;
}

I know i’ve got a lot of nonsense commented out, but there were certain situations during the section in which i doubted about how something worked, so if i get the doubt again, i just comment it out to see what happens. Cheers to everyone reading!

Privacy & Terms