Small game improvement

I’m not a beginner, so from the first lesson I understood the meaning of all the code. I made a slight improvement, the player now knows one of the numbers and only needs to guess the remaining 2. I think that makes the game a little more honest on higher difficulties.

#include <iostream>
#include <ctime>

int ChooseKnownNumber(int CodeA, int CodeB, int CodeC)
{
	int ReturnNumber = 1;
	int IndexNumber = 1 + rand() % 3;

	switch (IndexNumber)
	{
	case 1:
		ReturnNumber = CodeA;
		break;
	case 2:
		ReturnNumber = CodeB;
		break;
	case 3:
		ReturnNumber = CodeC;
		break;
	default:
		break;
	}

	return ReturnNumber;
}

void PrintInroduction(int Difficulty)
{
	std::cout << "You're a secret agent breaking into level " << Difficulty;
	std::cout << " secure server room...\nEnter the correct code to continue...\n\n";
}

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

	//Generate Code
	const int CodeA = rand() % Difficulty + Difficulty;
	const int CodeB = rand() % Difficulty + Difficulty;
	const int CodeC = rand() % Difficulty + Difficulty;

	const int KnownNumber = ChooseKnownNumber(CodeA, CodeB, CodeC);
	const int CodeSum = CodeA + CodeB + CodeC;
	const int CodeProduct = CodeA * CodeB * CodeC;

	std::cout << "+ There are 3 numbers in the code";
	std::cout << "\n+ One of numbers is: " << KnownNumber;
	std::cout << "\n+ The codes add-up to: " << CodeSum;
	std::cout << "\n+ The codes multiply to give: " << CodeProduct << std::endl;

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

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

	if (GuessSum == CodeSum && GuessProduct == CodeProduct)
	{
		std::cout << "\n*** Well done agent! You have extracted a file! Keep going! ***\n\n";
		return true;
	}
	else
	{
		std::cout << "\n*** You entered the wrong code! Careful agent! Try again! ***\n\n";
		return false;
	}
}

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

	int LevelDifficulty = 1;
	int const MaxDifficulty = 10;

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

		if (bLevelComplete)
			LevelDifficulty++;
		
	}

	std::cout << "WOW - You're a master hacker!\n";
	return 0; // exit with no error code
}
1 Like

Once you start getting it you feel really good.

Privacy & Terms